@piwitests/reporter 0.63.0 → 0.65.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.
@@ -61,7 +61,7 @@ __export(capture_fixtures_exports, {
61
61
  stopResourceLedger: () => stopResourceLedger
62
62
  });
63
63
  module.exports = __toCommonJS(capture_fixtures_exports);
64
- var path15 = __toESM(require("path"));
64
+ var path18 = __toESM(require("path"));
65
65
  var import_node_zlib2 = require("zlib");
66
66
 
67
67
  // ../picker-dom/src/probe.ts
@@ -520,8 +520,8 @@ function installPickerOverlay(arg) {
520
520
  return root && root !== doc && root.host ? root.host : null;
521
521
  };
522
522
  const targetOf = (e) => {
523
- const path16 = typeof e.composedPath === "function" ? e.composedPath() : null;
524
- const first = path16 && path16.length ? path16[0] : null;
523
+ const path19 = typeof e.composedPath === "function" ? e.composedPath() : null;
524
+ const first = path19 && path19.length ? path19[0] : null;
525
525
  return first && first.nodeType === 1 ? first : e.target;
526
526
  };
527
527
  const buildChain = (raw) => {
@@ -826,14 +826,14 @@ function showAnchorPicker(arg) {
826
826
  } catch {
827
827
  shadowRoots.length = 0;
828
828
  }
829
- const within3 = (node2, scope) => {
829
+ const within4 = (node2, scope) => {
830
830
  if (scope === doc) return true;
831
831
  for (let n = node2; n; n = parentOf(n)) if (n === scope) return true;
832
832
  return false;
833
833
  };
834
834
  const queryAll = (scope, sel) => {
835
835
  const found = Array.from(scope.querySelectorAll(sel));
836
- for (const sr of shadowRoots) if (within3(sr.host, scope)) found.push(...Array.from(sr.querySelectorAll(sel)));
836
+ for (const sr of shadowRoots) if (within4(sr.host, scope)) found.push(...Array.from(sr.querySelectorAll(sel)));
837
837
  return found;
838
838
  };
839
839
  const leafCountable = !!leafTestId || roleOf2(el) === leafRole;
@@ -1222,8 +1222,22 @@ function showPauseBar(arg) {
1222
1222
  cleanup();
1223
1223
  g.__piwiPauseState = choice;
1224
1224
  };
1225
+ const pageTakesEscape = (e) => {
1226
+ const path19 = typeof e.composedPath === "function" ? e.composedPath() : [e.target];
1227
+ const el = path19.find((node) => node && node.nodeType === 1);
1228
+ if (el && !bar.contains(el) && typeof el.closest === "function") {
1229
+ if (el.closest('dialog[open],[role="dialog"],[role="alertdialog"],[role="listbox"],[role="menu"]')) return true;
1230
+ const popup = '[aria-expanded="true"]:is([role="combobox"],[aria-haspopup]:not([aria-haspopup="false"]))';
1231
+ if (el.matches(popup)) return true;
1232
+ }
1233
+ try {
1234
+ return !!doc.querySelector("dialog:modal");
1235
+ } catch {
1236
+ return false;
1237
+ }
1238
+ };
1225
1239
  const onKey = (e) => {
1226
- if (e.key !== "Escape") return;
1240
+ if (e.key !== "Escape" || pageTakesEscape(e)) return;
1227
1241
  e.preventDefault();
1228
1242
  e.stopImmediatePropagation();
1229
1243
  done("resume");
@@ -1240,7 +1254,9 @@ function showPauseBar(arg) {
1240
1254
  ...arg.record ? [
1241
1255
  ["Record here", "record", "Record steps in this page: the editor writes them before this line", false]
1242
1256
  ] : [],
1243
- ...arg.failure ? [] : [["Finish", "finish", "Run on and pause no more in this test", false]],
1257
+ ...arg.failure ? [] : [
1258
+ ["Finish", "finish", "Run the test on without stopping at a breakpoint again in this attempt", false]
1259
+ ],
1244
1260
  ...arg.end && !arg.failure ? [
1245
1261
  ["End the test", "end", "Skip the rest of this test: it is reported as skipped", false]
1246
1262
  ] : []
@@ -1276,6 +1292,102 @@ function takePauseState() {
1276
1292
  return typeof state === "string" ? state : null;
1277
1293
  }
1278
1294
 
1295
+ // ../picker-dom/src/overlay-stop.ts
1296
+ function showStopHighlight(elements, arg) {
1297
+ const g = globalThis;
1298
+ const doc = g.document;
1299
+ const gone = g.__piwiStopHighlightsGone instanceof Set ? g.__piwiStopHighlightsGone : /* @__PURE__ */ new Set();
1300
+ g.__piwiStopHighlightsGone = gone;
1301
+ if (!doc || !doc.documentElement) return 0;
1302
+ const drawn = doc.getElementById(`__piwi_stop_highlight_${arg.id}`);
1303
+ const targets = gone.has(arg.id) ? [] : elements.slice(0, 500);
1304
+ const shownIn = (layer2) => Array.from(layer2.children).filter((box) => box.dataset.box && box.style.display !== "none").length;
1305
+ const raise = (layer2) => {
1306
+ if (!layer2.hasAttribute("popover")) return;
1307
+ try {
1308
+ if (layer2.matches(":popover-open")) layer2.hidePopover();
1309
+ layer2.showPopover();
1310
+ } catch {
1311
+ layer2.removeAttribute("popover");
1312
+ }
1313
+ };
1314
+ const before = drawn?.__piwiTargets;
1315
+ if (drawn && before && before.length === targets.length && before.every((el, i) => el === targets[i])) {
1316
+ if (targets.length) raise(drawn);
1317
+ drawn.__piwiPlace?.();
1318
+ return shownIn(drawn);
1319
+ }
1320
+ drawn?.remove();
1321
+ if (!targets.length) return 0;
1322
+ const Z = 2147483600;
1323
+ const MONO = "ui-monospace,SFMono-Regular,Menlo,Consolas,monospace";
1324
+ const layer = doc.createElement("div");
1325
+ layer.id = `__piwi_stop_highlight_${arg.id}`;
1326
+ layer.setAttribute("data-piwi-stop-highlight", arg.kind);
1327
+ layer.setAttribute("aria-hidden", "true");
1328
+ layer.setAttribute("popover", "manual");
1329
+ layer.style.cssText = `position:fixed;inset:auto;top:0;left:0;width:0;height:0;margin:0;padding:0;border:0;background:transparent;overflow:visible;pointer-events:none;z-index:${Z - 1};`;
1330
+ layer.__piwiTargets = targets;
1331
+ const look = arg.kind === "call" ? "border:2px solid #a855f7;background:rgba(168,85,247,.14);border-radius:4px;box-shadow:0 0 0 1px rgba(255,255,255,.9),0 0 0 3px rgba(59,7,100,.55);" : "border:2px dashed #a78bfa;background:rgba(167,139,250,.15);border-radius:3px;box-shadow:0 0 0 1px rgba(255,255,255,.8);";
1332
+ const boxes = targets.map(() => {
1333
+ const box = doc.createElement("div");
1334
+ box.dataset.box = "1";
1335
+ box.style.cssText = `position:fixed;display:none;box-sizing:border-box;pointer-events:none;${look}`;
1336
+ layer.appendChild(box);
1337
+ return box;
1338
+ });
1339
+ const label = doc.createElement("div");
1340
+ label.style.cssText = `position:fixed;display:none;pointer-events:none;box-sizing:border-box;max-width:min(620px,92vw);background:#0b1120;color:#f9fafb;border:1px solid #7c3aed;border-radius:6px;padding:2px 7px;font:12px/1.45 ${MONO};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;box-shadow:0 2px 10px rgba(0,0,0,.4);`;
1341
+ label.textContent = arg.label;
1342
+ layer.appendChild(label);
1343
+ doc.documentElement.appendChild(layer);
1344
+ raise(layer);
1345
+ const place = () => {
1346
+ let first = null;
1347
+ targets.forEach((el, i) => {
1348
+ const box = boxes[i];
1349
+ const rect = el && el.isConnected && typeof el.getBoundingClientRect === "function" ? el.getBoundingClientRect() : null;
1350
+ if (!rect || rect.width === 0 && rect.height === 0) {
1351
+ box.style.display = "none";
1352
+ return;
1353
+ }
1354
+ box.style.display = "block";
1355
+ box.style.left = `${rect.left - 2}px`;
1356
+ box.style.top = `${rect.top - 2}px`;
1357
+ box.style.width = `${rect.width + 4}px`;
1358
+ box.style.height = `${rect.height + 4}px`;
1359
+ first ??= rect;
1360
+ });
1361
+ if (first && arg.label) {
1362
+ label.style.display = "block";
1363
+ const height = label.offsetHeight || 20;
1364
+ const above = first.top - 2 - height - 4;
1365
+ label.style.left = `${Math.max(4, first.left - 2)}px`;
1366
+ label.style.top = `${above >= 4 ? above : first.bottom + 6}px`;
1367
+ } else {
1368
+ label.style.display = "none";
1369
+ }
1370
+ };
1371
+ layer.__piwiPlace = place;
1372
+ const follow = () => {
1373
+ if (!layer.isConnected) return;
1374
+ place();
1375
+ g.requestAnimationFrame(follow);
1376
+ };
1377
+ follow();
1378
+ return shownIn(layer);
1379
+ }
1380
+ function removeStopHighlight(id) {
1381
+ const g = globalThis;
1382
+ const gone = g.__piwiStopHighlightsGone instanceof Set ? g.__piwiStopHighlightsGone : /* @__PURE__ */ new Set();
1383
+ g.__piwiStopHighlightsGone = gone;
1384
+ gone.add(id);
1385
+ const layer = g.document?.getElementById(`__piwi_stop_highlight_${id}`);
1386
+ if (!layer) return false;
1387
+ layer.remove();
1388
+ return true;
1389
+ }
1390
+
1279
1391
  // ../core/src/locator-chain.ts
1280
1392
  var LOCATING_METHODS = /* @__PURE__ */ new Set([
1281
1393
  "getByRole",
@@ -2004,21 +2116,21 @@ var MAX_INDETERMINATE = 20;
2004
2116
  var STEP = String.raw`[a-zA-Z][\w.-]*:[1-9]\d*`;
2005
2117
  var LEVEL = `${STEP}(?:/${STEP})*`;
2006
2118
  var ELEMENT_PATH_RE = new RegExp(`^${LEVEL}(?:\\|${LEVEL})*$`);
2007
- function isElementPath(path16) {
2008
- return typeof path16 === "string" && path16.length <= ELEMENT_PATH_MAX_CHARS && ELEMENT_PATH_RE.test(path16);
2119
+ function isElementPath(path19) {
2120
+ return typeof path19 === "string" && path19.length <= ELEMENT_PATH_MAX_CHARS && ELEMENT_PATH_RE.test(path19);
2009
2121
  }
2010
2122
  var offsetOf = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 1e7 ? v : null;
2011
2123
  function elementRef(v) {
2012
2124
  if (!v || typeof v !== "object") return null;
2013
- const { path: path16, label } = v;
2014
- if (!isElementPath(path16)) return null;
2015
- return { path: path16, label: typeof label === "string" ? label.slice(0, ELEMENT_LABEL_MAX_CHARS) : "" };
2125
+ const { path: path19, label } = v;
2126
+ if (!isElementPath(path19)) return null;
2127
+ return { path: path19, label: typeof label === "string" ? label.slice(0, ELEMENT_LABEL_MAX_CHARS) : "" };
2016
2128
  }
2017
2129
  function textPoint(v) {
2018
2130
  if (!v || typeof v !== "object") return null;
2019
- const { path: path16, offset } = v;
2131
+ const { path: path19, offset } = v;
2020
2132
  const at = offsetOf(offset);
2021
- return isElementPath(path16) && at !== null ? { path: path16, offset: at } : null;
2133
+ return isElementPath(path19) && at !== null ? { path: path19, offset: at } : null;
2022
2134
  }
2023
2135
  function sanitizePageInteraction(raw) {
2024
2136
  if (!raw || typeof raw !== "object") return {};
@@ -2425,6 +2537,7 @@ var ATTACHMENT_NAMES = {
2425
2537
  codeReach: "piwi-code-reach",
2426
2538
  browserCoverage: "piwi-browser-coverage",
2427
2539
  browserFunctions: "piwi-browser-functions",
2540
+ browserLines: "piwi-browser-lines",
2428
2541
  cssCoverage: "piwi-css-coverage",
2429
2542
  cssRules: "piwi-css-rules",
2430
2543
  serverCoverageRequests: "piwi-server-coverage-requests",
@@ -2840,16 +2953,68 @@ function relativeTestPath(file, base) {
2840
2953
  return path4.relative(base, file).split(path4.sep).join("/");
2841
2954
  }
2842
2955
 
2956
+ // ../core/src/glob.ts
2957
+ function dotTakes(char) {
2958
+ return char !== "\n" && char !== "\r" && char !== "\u2028" && char !== "\u2029";
2959
+ }
2960
+ function canonicalize(char) {
2961
+ const upper = char.toUpperCase();
2962
+ if (upper.length !== 1) return char;
2963
+ return char.charCodeAt(0) >= 128 && upper.charCodeAt(0) < 128 ? char : upper;
2964
+ }
2965
+ function compileGlob(tokens, ignoreCase = false) {
2966
+ const steps = ignoreCase ? tokens.map((token) => token.kind === "char" ? { ...token, char: canonicalize(token.char) } : token) : tokens;
2967
+ const end = steps.length;
2968
+ return (text) => {
2969
+ const seen = new Int32Array(end + 1).fill(-1);
2970
+ let current = [];
2971
+ let next = [];
2972
+ const reach = (list, from, step) => {
2973
+ for (let state = from; seen[state] !== step; state++) {
2974
+ seen[state] = step;
2975
+ list.push(state);
2976
+ if (state === end || steps[state].kind !== "run") break;
2977
+ }
2978
+ };
2979
+ reach(current, 0, 0);
2980
+ for (let i = 0; i < text.length; i++) {
2981
+ const char = ignoreCase ? canonicalize(text[i]) : text[i];
2982
+ const dot = dotTakes(char);
2983
+ for (const state of current) {
2984
+ if (state === end) continue;
2985
+ const token = steps[state];
2986
+ const takes = token.kind === "char" ? token.char === char : token.slash ? dot : char !== "/";
2987
+ if (takes) reach(next, token.kind === "run" ? state : state + 1, i + 1);
2988
+ }
2989
+ if (next.length === 0) return false;
2990
+ [current, next] = [next, current];
2991
+ next.length = 0;
2992
+ }
2993
+ return seen[end] === text.length;
2994
+ };
2995
+ }
2996
+
2843
2997
  // src/internal/probe/plan.ts
2844
2998
  function parseRouteKey(routeKey2) {
2845
2999
  const space = routeKey2.indexOf(" ");
2846
3000
  if (space < 0) return { method: "", pattern: routeKey2 };
2847
3001
  return { method: routeKey2.slice(0, space).toUpperCase(), pattern: routeKey2.slice(space + 1) };
2848
3002
  }
2849
- function patternToRegex(pattern) {
2850
- const path16 = pattern.split("?")[0] ?? pattern;
2851
- const escaped = path16.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/:[A-Za-z0-9_]+/g, "[^/]+");
2852
- return new RegExp(`^${escaped}$`);
3003
+ var ROUTE_PARAM = /:[A-Za-z0-9_]+/y;
3004
+ function routePatternMatcher(pattern) {
3005
+ const path19 = pattern.split("?")[0] ?? pattern;
3006
+ const tokens = [];
3007
+ for (let i = 0; i < path19.length; i++) {
3008
+ ROUTE_PARAM.lastIndex = i;
3009
+ const param = ROUTE_PARAM.exec(path19);
3010
+ if (param) {
3011
+ tokens.push({ kind: "one", slash: false }, { kind: "run", slash: false });
3012
+ i += param[0].length - 1;
3013
+ } else {
3014
+ tokens.push({ kind: "char", char: path19[i] });
3015
+ }
3016
+ }
3017
+ return compileGlob(tokens);
2853
3018
  }
2854
3019
  function suitePathEqual(a, b) {
2855
3020
  if (!a || !b || a.length !== b.length) return false;
@@ -2871,13 +3036,13 @@ function matchProbeItem(plan, test) {
2871
3036
  function requestMatchesRoute(method, url, routeKey2) {
2872
3037
  const { method: rm, pattern } = parseRouteKey(routeKey2);
2873
3038
  if (rm && rm !== method.toUpperCase()) return false;
2874
- let path16;
3039
+ let path19;
2875
3040
  try {
2876
- path16 = new URL(url).pathname;
3041
+ path19 = new URL(url).pathname;
2877
3042
  } catch {
2878
- path16 = url.split("?")[0] ?? url;
3043
+ path19 = url.split("?")[0] ?? url;
2879
3044
  }
2880
- return patternToRegex(pattern).test(path16);
3045
+ return routePatternMatcher(pattern)(path19);
2881
3046
  }
2882
3047
  function createProbeState() {
2883
3048
  return { navigated: false, matches: 0 };
@@ -2899,10 +3064,10 @@ function isProbeMode() {
2899
3064
  function loadPlan() {
2900
3065
  if (planCache !== void 0) return planCache;
2901
3066
  planCache = null;
2902
- const path16 = process.env[PIWI_PROBE_ENV.plan];
2903
- if (path16) {
3067
+ const path19 = process.env[PIWI_PROBE_ENV.plan];
3068
+ if (path19) {
2904
3069
  try {
2905
- planCache = JSON.parse(fs3.readFileSync(path16, "utf8"));
3070
+ planCache = JSON.parse(fs3.readFileSync(path19, "utf8"));
2906
3071
  } catch {
2907
3072
  planCache = null;
2908
3073
  }
@@ -2919,17 +3084,27 @@ function probeItemForTest(test) {
2919
3084
  function classifyProbeHandled(signals) {
2920
3085
  const blank = signals.blankPage === true;
2921
3086
  if ((signals.pageErrors ?? 0) > 0 || signals.backendError && blank) return "unhandled";
2922
- return signals.consoleErrors > 0 || signals.dialogs > 0 || signals.backendError || blank ? "degraded" : "graceful";
3087
+ const backendDegraded = signals.backendError && signals.faultIsTheError !== true;
3088
+ return signals.consoleErrors > 0 || signals.dialogs > 0 || backendDegraded || blank ? "degraded" : "graceful";
3089
+ }
3090
+ var SELF_ERROR_FAULTS = /* @__PURE__ */ new Set(["throw", "status"]);
3091
+ function faultIsTheError(fault) {
3092
+ return SELF_ERROR_FAULTS.has(fault);
3093
+ }
3094
+ var RESOURCE_ERROR_TEXT = /^Failed to load resource\b/;
3095
+ function probeConsoleErrors(entries) {
3096
+ return entries.filter((e) => e.type === "error" && !(typeof e.text === "string" && RESOURCE_ERROR_TEXT.test(e.text))).length;
2923
3097
  }
2924
3098
  function outcomeFromStatus(status, applied) {
2925
3099
  if (!applied) return "inconclusive";
2926
- return status === "failed" || status === "timedOut" || status === "interrupted" ? "noticed" : "not-noticed";
3100
+ if (status === "failed" || status === "timedOut") return "noticed";
3101
+ return status === "passed" ? "not-noticed" : "inconclusive";
2927
3102
  }
2928
3103
  function recordProbeOutcome(line) {
2929
- const path16 = process.env[PIWI_PROBE_ENV.results];
2930
- if (!path16) return;
3104
+ const path19 = process.env[PIWI_PROBE_ENV.results];
3105
+ if (!path19) return;
2931
3106
  try {
2932
- fs3.appendFileSync(path16, `${JSON.stringify(line)}
3107
+ fs3.appendFileSync(path19, `${JSON.stringify(line)}
2933
3108
  `);
2934
3109
  } catch {
2935
3110
  }
@@ -2966,23 +3141,26 @@ function dropOneField(body) {
2966
3141
  } catch {
2967
3142
  return body;
2968
3143
  }
3144
+ let dropped = false;
2969
3145
  if (Array.isArray(parsed2)) {
2970
3146
  let key;
2971
3147
  for (const el of parsed2) {
2972
3148
  if (el && typeof el === "object" && !Array.isArray(el)) {
2973
3149
  key ??= Object.keys(el)[0];
2974
- if (key) delete el[key];
3150
+ if (key && Object.prototype.hasOwnProperty.call(el, key)) {
3151
+ delete el[key];
3152
+ dropped = true;
3153
+ }
2975
3154
  }
2976
3155
  }
2977
- return JSON.stringify(parsed2);
2978
- }
2979
- if (parsed2 && typeof parsed2 === "object") {
2980
- const obj = parsed2;
2981
- const key = Object.keys(obj)[0];
2982
- if (key) delete obj[key];
2983
- return JSON.stringify(obj);
3156
+ } else if (parsed2 && typeof parsed2 === "object") {
3157
+ const key = Object.keys(parsed2)[0];
3158
+ if (key) {
3159
+ delete parsed2[key];
3160
+ dropped = true;
3161
+ }
2984
3162
  }
2985
- return body;
3163
+ return dropped ? JSON.stringify(parsed2) : body;
2986
3164
  }
2987
3165
  function computeFault(fault, input2) {
2988
3166
  const base = {
@@ -3059,7 +3237,7 @@ function originOf(url) {
3059
3237
  return null;
3060
3238
  }
3061
3239
  }
3062
- var sleep = (ms) => new Promise((resolve5) => setTimeout(resolve5, Math.max(0, ms)));
3240
+ var sleep = (ms) => new Promise((resolve6) => setTimeout(resolve6, Math.max(0, ms)));
3063
3241
  async function performRouteAction(route, action, startedAt) {
3064
3242
  switch (action.kind) {
3065
3243
  case "abort":
@@ -3258,6 +3436,11 @@ var LONG_HEX_RE = /\b[0-9a-f]{8,}\b/gi;
3258
3436
  var SHORT_HEX_RE = /\b(?=[0-9a-f]*[a-f])(?=[0-9a-f]*[0-9])[0-9a-f]{6,7}\b/gi;
3259
3437
  var URL_RE = /\bhttps?:\/\/[^\s'"`)]+/gi;
3260
3438
  var EMAIL_RE = /\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b/gi;
3439
+ var STRICT_MODE_ELEMENTS_RE = /(resolved to \d+ elements?:)(?:\n[ \t]*(?:\d+\) [^\n]*|\.\.\.))+/g;
3440
+ var ISO_TIMESTAMP_RE = /\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:[.,]\d+)?)?(?:Z|[+-]\d{2}(?::?\d{2})?)?/g;
3441
+ var ABSOLUTE_PATH_RE = /(^|[^\w.~-])(?:\/(?:home|Users|root|__w|builds|github\/workspace|(?:private\/)?var\/folders)\/|[A-Za-z]:[\\/])(?:[^\s'"`()<>,;]*[\\/])?/gm;
3442
+ var TEMP_SUFFIX_RE = /([\\/][^\\/\s'"`()<>,;]*?[-_])(?=[a-z]{0,5}[A-Z0-9])[A-Za-z0-9]{6}(?![\w.-])/g;
3443
+ var UNDERSCORE_TOKEN_RE = /_([A-Za-z0-9]{8,})/g;
3261
3444
  var SELECTOR_OPTION_KEY_RE = /\b(name|hasText|hasNotText|has|placeholder|label|title|alt|exact)\s*:\s*(['"`])/gi;
3262
3445
  var LINE_TERMINATORS = /* @__PURE__ */ new Set(["\n", "\r", "\u2028", "\u2029"]);
3263
3446
  function closingQuoteIndex(text, quote) {
@@ -3304,8 +3487,15 @@ function classifyError(text) {
3304
3487
  if (/Timeout \d+m?s exceeded|TimeoutError|Timed out \d+m?s/i.test(text)) return "timeout";
3305
3488
  return "unknown";
3306
3489
  }
3490
+ function maskUnderscoreId(whole, token) {
3491
+ return /\d/.test(token) && /[A-Za-z]/.test(token) && !/^[A-Za-z]+\d+$/.test(token) ? "_<ID>" : whole;
3492
+ }
3493
+ function maskPaths(text) {
3494
+ return text.replace(ABSOLUTE_PATH_RE, "$1<PATH>/").replace(TEMP_SUFFIX_RE, "$1<TMP>");
3495
+ }
3307
3496
  function maskVolatile(text) {
3308
- return text.replace(/^(\s*(?:Received|Expected)[^:\n]*:).*$/gm, "$1 <VALUE>").replace(URL_RE, "<URL>").replace(EMAIL_RE, "<EMAIL>").replace(UUID_RE, "<UUID>").replace(LONG_HEX_RE, "<HASH>").replace(SHORT_HEX_RE, "<HASH>").replace(/([A-Za-z])?(\d+)/g, (whole, letter) => letter ? whole : "<N>");
3497
+ const structured = text.replace(STRICT_MODE_ELEMENTS_RE, "$1").replace(/^(\s*(?:Received|Expected)[^:\n]*:).*$/gm, "$1 <VALUE>").replace(URL_RE, "<URL>").replace(EMAIL_RE, "<EMAIL>").replace(ISO_TIMESTAMP_RE, "<TIMESTAMP>");
3498
+ return maskPaths(structured).replace(UUID_RE, "<UUID>").replace(UNDERSCORE_TOKEN_RE, maskUnderscoreId).replace(LONG_HEX_RE, "<HASH>").replace(SHORT_HEX_RE, "<HASH>").replace(/([A-Za-z])?(\d+)/g, (whole, letter) => letter ? whole : "<N>");
3309
3499
  }
3310
3500
  function extractErrorSignature(rawError) {
3311
3501
  const text = stripAnsi(rawError);
@@ -3640,83 +3830,534 @@ function recordFlakeResult(line) {
3640
3830
  }
3641
3831
  }
3642
3832
 
3643
- // ../core/src/error-text.ts
3644
- function joinErrorMessages(errors) {
3645
- if (!errors || errors.length === 0) return null;
3646
- const seen = /* @__PURE__ */ new Set();
3647
- const parts = [];
3648
- for (const err of errors) {
3649
- const msg = err.message ?? "";
3650
- if (!msg) continue;
3651
- const dedupeKey = msg.trim().slice(0, 200);
3652
- if (seen.has(dedupeKey)) continue;
3653
- seen.add(dedupeKey);
3654
- parts.push(msg);
3655
- }
3656
- return parts.join("\n---\n") || null;
3657
- }
3658
-
3659
- // ../core/src/coverage.ts
3660
- var MAX_COVERAGE_FILES = 2e3;
3661
- var MAX_COVERAGE_RANGES = 1e4;
3662
- var MAX_LINE = 1e6;
3663
- var MAX_PATH_LENGTH = 500;
3664
- var BLOB_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
3665
- function isRecord(value) {
3666
- return typeof value === "object" && value !== null && !Array.isArray(value);
3833
+ // ../core/src/mask.ts
3834
+ var DATA_URI_RE = /\bdata:[a-z0-9.+-]+\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/gi;
3835
+ var JWT_RE = /\beyJ[\w-]{10,}\.[\w-]{5,}\.[\w-]{5,}\b/g;
3836
+ var LONG_HEX_RE2 = /\b[0-9a-f]{32,}\b/gi;
3837
+ function maskTokenLike(text) {
3838
+ return text.replace(DATA_URI_RE, "data:[masked]").replace(JWT_RE, "[masked-token]").replace(LONG_HEX_RE2, "[masked-hex]");
3667
3839
  }
3668
- function isRuntime(value) {
3669
- return value === "browser" || value === "server";
3840
+ var CREDENTIAL_PARAM_RE = /token|code|secret|password|passwd|pwd|key|session|auth|sig|credential|assertion|nonce|otp|jwt/i;
3841
+ function maskUrlFragment(hash) {
3842
+ const body = hash.startsWith("#") ? hash.slice(1) : hash;
3843
+ const query = body.indexOf("?");
3844
+ const route = query >= 0 ? body.slice(0, query) : body.includes("=") ? "" : body;
3845
+ const params = query >= 0 ? body.slice(query + 1) : body.includes("=") ? body : null;
3846
+ const masked = params === null ? null : params.split("&").map((param) => {
3847
+ const eq = param.indexOf("=");
3848
+ if (eq < 0) return maskTokenLike(param);
3849
+ const name = param.slice(0, eq);
3850
+ const value = param.slice(eq + 1);
3851
+ return `${name}=${value && CREDENTIAL_PARAM_RE.test(name) ? "[masked]" : maskTokenLike(value)}`;
3852
+ }).join("&");
3853
+ const out = maskTokenLike(route) + (masked === null ? "" : query >= 0 ? `?${masked}` : masked);
3854
+ return hash.startsWith("#") ? `#${out}` : out;
3670
3855
  }
3671
- function isLine(value) {
3672
- return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= MAX_LINE;
3856
+ var HIDDEN_VALUE = "<hidden>";
3857
+ var SECRET_AUTOCOMPLETE = [
3858
+ "current-password",
3859
+ "new-password",
3860
+ "one-time-code",
3861
+ "cc-number",
3862
+ "cc-csc"
3863
+ ];
3864
+ var SECRET_FIELD_SELECTOR = [
3865
+ 'input[type="password" i]',
3866
+ ...SECRET_AUTOCOMPLETE.flatMap((token) => [
3867
+ `input[autocomplete~="${token}" i]`,
3868
+ `textarea[autocomplete~="${token}" i]`
3869
+ ])
3870
+ ].join(", ");
3871
+ var SECRET_WORDS = /* @__PURE__ */ new Set([
3872
+ "pass",
3873
+ "password",
3874
+ "passwd",
3875
+ "passphrase",
3876
+ "passcode",
3877
+ "pwd",
3878
+ "secret",
3879
+ "secrets",
3880
+ "token",
3881
+ "tokens",
3882
+ "jwt",
3883
+ "bearer",
3884
+ "sig",
3885
+ "signature",
3886
+ "key",
3887
+ "keys",
3888
+ "apikey",
3889
+ "auth",
3890
+ "oauth",
3891
+ "authorization",
3892
+ "session",
3893
+ "sessionid",
3894
+ "jsessionid",
3895
+ "sid",
3896
+ "cookie",
3897
+ "cookies",
3898
+ "credential",
3899
+ "credentials",
3900
+ "otp",
3901
+ "refresh",
3902
+ "csrf",
3903
+ "xsrf"
3904
+ ]);
3905
+ var SECRET_NAMES = /* @__PURE__ */ new Set(["code", "pin"]);
3906
+ function nameWords(name) {
3907
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z])(?=[A-Z][a-z])/g, "$1 ").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
3673
3908
  }
3674
- function validRanges(raw) {
3675
- if (!Array.isArray(raw)) return [];
3676
- const out = [];
3677
- for (const item of raw) {
3678
- if (!Array.isArray(item) || item.length !== 2) continue;
3679
- const [start, end] = item;
3680
- if (isLine(start) && isLine(end) && start <= end) out.push([start, end]);
3909
+ function isSecretName(name) {
3910
+ let secret = namesRead.get(name);
3911
+ if (secret === void 0) {
3912
+ secret = SECRET_NAMES.has(name.trim().toLowerCase()) || nameWords(name).some((word) => SECRET_WORDS.has(word));
3913
+ if (namesRead.size >= 1024) namesRead.clear();
3914
+ namesRead.set(name, secret);
3681
3915
  }
3682
- return out.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
3916
+ return secret;
3683
3917
  }
3684
- function normalizeLineRanges(ranges) {
3685
- const out = [];
3686
- for (const range of validRanges(ranges)) {
3687
- const last = out[out.length - 1];
3688
- if (last && range[0] <= last[1] + 1) last[1] = Math.max(last[1], range[1]);
3689
- else out.push(range);
3918
+ var namesRead = /* @__PURE__ */ new Map();
3919
+ var SHAPES = [
3920
+ { re: /\beyJ[\w-]{5,}\.[\w-]{5,}\.[\w-]*/g, starts: ["eyJ"] },
3921
+ { re: /\bBearer(?:\s+|%20)[\w.~+/-]{8,}=*/gi, starts: ["Bearer"] },
3922
+ {
3923
+ re: /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{8,}/g,
3924
+ starts: ["sk_live_", "sk_test_", "rk_live_", "rk_test_"]
3925
+ },
3926
+ { re: /\bwhsec_[A-Za-z0-9]{20,}/g, starts: ["whsec_"] },
3927
+ { re: /\bsk-(?=[\w-]{0,200}\d)(?=[\w-]{0,200}[A-Z])[\w-]{32,}/g, starts: ["sk-"] },
3928
+ { re: /\bglpat-[\w-]{20,}/g, starts: ["glpat-"] },
3929
+ { re: /\bnpm_[A-Za-z0-9]{36}\b/g, starts: ["npm_"] },
3930
+ { re: /\bSK[0-9a-f]{32}\b/g, starts: ["SK"] },
3931
+ { re: /\bAKIA[0-9A-Z]{16}\b/g, starts: ["AKIA"] },
3932
+ { re: /\bAIza[\w-]{30,}/g, starts: ["AIza"] },
3933
+ { re: /\bgh[opsu]_[A-Za-z0-9]{20,}/g, starts: ["gho_", "ghp_", "ghs_", "ghu_"] },
3934
+ { re: /\bgithub_pat_\w{20,}/g, starts: ["github_pat_"] },
3935
+ { re: /\bxox[abprs]-[\w-]{8,}/g, starts: ["xoxa-", "xoxb-", "xoxp-", "xoxr-", "xoxs-"] },
3936
+ // Piwi's: an API key or the desktop app's token, an extension's device code, an MCP client's secret, authorization
3937
+ // code, access and refresh tokens, a share link's and an assistant turn's token; a live view's key.
3938
+ {
3939
+ re: /\b(?:pd[acor]?|mcps|psl|pwt)_[0-9a-f]{32,}/g,
3940
+ starts: ["pd_", "pda_", "pdc_", "pdo_", "pdr_", "mcps_", "psl_", "pwt_"]
3941
+ },
3942
+ { re: /\bpdl_[\w-]{40,}/g, starts: ["pdl_"] }
3943
+ ];
3944
+ var SECRET_SHAPES = SHAPES.map((shape) => shape.re);
3945
+ var SECRET_SHAPE_STARTS = SHAPES.flatMap(
3946
+ ({ re, starts }) => starts.map((start) => ({ start, anyCase: re.flags.includes("i") }))
3947
+ );
3948
+ var COLORED_SHAPES = SECRET_SHAPES.map(
3949
+ (re) => new RegExp(`(\\u001b\\[[\\d;]*m)${re.source.replace(/^\\b/, "")}`, re.flags)
3950
+ );
3951
+ var WHOLE_SHAPES = SECRET_SHAPES.map(
3952
+ (re) => new RegExp(`^(?:${re.source})$`, re.flags.replace("g", ""))
3953
+ );
3954
+ var BASIC = /\bBasic\s+([A-Za-z0-9+/]{4,}={0,2})(?![\w+/=])/g;
3955
+ var PEM_BEGIN = /-----BEGIN ([A-Z0-9 ]{0,40}PRIVATE KEY)-----/g;
3956
+ var SET_COOKIE = /(\bSet-Cookie:[ \t]*[^=;\s]{1,256}=)([^;\r\n]{1,4096})/gi;
3957
+ var COOKIE_LINE = /((?<![\w-])Cookie:[ \t]*)([^\r\n]{1,16384})/gi;
3958
+ var JSON_FIELD = /("((?:[^"\\\r\n]|\\.){1,256})"\s*:\s*")((?:[^"\\\r\n]|\\.){1,4096})"/g;
3959
+ var TOKEN_RUN = /[A-Za-z0-9+/_-]{40,}={0,2}/g;
3960
+ var MIN_RANDOM = 40;
3961
+ var BASE64_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3962
+ function base64OfText(run) {
3963
+ let bits = 0;
3964
+ let acc = 0;
3965
+ let bytes = 0;
3966
+ let printable = 0;
3967
+ for (const c of run.replace(/=+$/, "")) {
3968
+ const digit = BASE64_DIGITS.indexOf(c === "-" ? "+" : c === "_" ? "/" : c);
3969
+ if (digit < 0) return false;
3970
+ acc = (acc << 6 | digit) & 65535;
3971
+ bits += 6;
3972
+ if (bits < 8) continue;
3973
+ bits -= 8;
3974
+ const byte = acc >> bits & 255;
3975
+ bytes++;
3976
+ if (byte >= 32 && byte < 127 || byte === 9 || byte === 10 || byte === 13) printable++;
3690
3977
  }
3691
- return out;
3978
+ return bytes > 0 && printable * 10 >= bytes * 9;
3692
3979
  }
3693
- function normalizeFunctionRanges(ranges) {
3694
- const out = [];
3695
- for (const range of validRanges(ranges)) {
3696
- const last = out[out.length - 1];
3697
- if (!last || last[0] !== range[0] || last[1] !== range[1]) out.push(range);
3698
- }
3699
- return out;
3980
+ function bitsPerChar(text) {
3981
+ const counts = /* @__PURE__ */ new Map();
3982
+ for (const c of text) counts.set(c, (counts.get(c) ?? 0) + 1);
3983
+ let bits = 0;
3984
+ for (const n of counts.values()) bits -= n / text.length * Math.log2(n / text.length);
3985
+ return bits;
3700
3986
  }
3701
- function normalizeCoveragePath(raw) {
3702
- if (typeof raw !== "string" || raw.length > MAX_PATH_LENGTH || raw.includes("\0")) return null;
3703
- const path16 = raw.replace(/\\/g, "/").replace(/^\.\//, "");
3704
- if (!path16 || path16.startsWith("../") || path16.startsWith("/") || /^[A-Za-z]:\//.test(path16)) return null;
3705
- if (/(^|\/)node_modules\//.test(path16)) return null;
3706
- return path16;
3987
+ function looksRandom(text) {
3988
+ if (text.length < MIN_RANDOM || !/[A-Z]/.test(text) || !/[a-z]/.test(text) || !/\d/.test(text)) return false;
3989
+ let letters = 0;
3990
+ for (const c of text) if (c >= "a" && c <= "z" || c >= "A" && c <= "Z") letters++;
3991
+ let wordy = 0;
3992
+ for (const run of text.matchAll(/[a-z]{6,}|[A-Z]{6,}/g)) wordy += run[0].length;
3993
+ return wordy * 5 <= letters && bitsPerChar(text) >= 4 && !base64OfText(text);
3707
3994
  }
3708
- function fileEntry(path16, runtime, blob, functions = [], lines = []) {
3709
- const file = { path: path16, runtime };
3710
- if (blob && (functions.length > 0 || lines.length > 0)) file.blob = blob;
3711
- if (functions.length > 0) file.functions = functions;
3712
- if (lines.length > 0) file.lines = lines;
3713
- return file;
3995
+ function isBasicCredential(encoded) {
3996
+ const text = encoded.replace(/=+$/, "");
3997
+ if (text.length % 4 === 1) return false;
3998
+ let decoded = "";
3999
+ let bits = 0;
4000
+ let acc = 0;
4001
+ for (const c of text) {
4002
+ const digit = BASE64_DIGITS.indexOf(c);
4003
+ if (digit < 0) return false;
4004
+ acc = (acc << 6 | digit) & 65535;
4005
+ bits += 6;
4006
+ if (bits < 8) continue;
4007
+ bits -= 8;
4008
+ decoded += String.fromCharCode(acc >> bits & 255);
4009
+ }
4010
+ return /^[\x20-\x7e]+:[\x20-\x7e]*$/.test(decoded);
3714
4011
  }
3715
- function captureOf(files, incomplete) {
3716
- return incomplete ? { v: 1, files, incomplete: true } : { v: 1, files };
4012
+ function isSecretValue(value) {
4013
+ const text = value.trim();
4014
+ if (text.length < 10 || text.length > 4096) return false;
4015
+ if (WHOLE_SHAPES.some((re) => re.test(text))) return true;
4016
+ const basic = /^Basic\s+([A-Za-z0-9+/]{4,}={0,2})$/.exec(text);
4017
+ if (basic && isBasicCredential(basic[1])) return true;
4018
+ if (/^-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY-----/.test(text)) return true;
4019
+ return /^[A-Za-z0-9+/_-]{40,}={0,2}$/.test(text) && looksRandom(text);
3717
4020
  }
3718
- function compareFiles(a, b) {
3719
- if (a.path !== b.path) return a.path < b.path ? -1 : 1;
4021
+ var URL_IN_TEXT = /\b[a-z][a-z0-9+.-]{0,31}:\/\/[^\s"'<>`]+/gi;
4022
+ var URL_PARTS = /^(?:([a-z][a-z0-9+.-]*:)?\/\/([^/?#]*))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?$/i;
4023
+ function decodeSafe(text) {
4024
+ try {
4025
+ return decodeURIComponent(text);
4026
+ } catch {
4027
+ return text;
4028
+ }
4029
+ }
4030
+ function hider(count) {
4031
+ return () => {
4032
+ count.n++;
4033
+ return HIDDEN_VALUE;
4034
+ };
4035
+ }
4036
+ function hideSecretShapes(text, count = { n: 0 }) {
4037
+ const hide = hider(count);
4038
+ let out = text;
4039
+ for (const shape of SECRET_SHAPES) out = out.replace(shape, () => hide());
4040
+ if (out.includes("\x1B[")) {
4041
+ for (const shape of COLORED_SHAPES) out = out.replace(shape, (_all, color) => `${color}${hide()}`);
4042
+ }
4043
+ return out;
4044
+ }
4045
+ function hideParams(params, count) {
4046
+ const hide = hider(count);
4047
+ return params.split(/([&;])/).map((part, i) => {
4048
+ const eq = part.indexOf("=");
4049
+ if (i % 2 === 1 || eq < 0) return part;
4050
+ const name = part.slice(0, eq);
4051
+ const value = part.slice(eq + 1);
4052
+ const decoded = decodeSafe(value);
4053
+ if (!value || decoded === HIDDEN_VALUE) return part;
4054
+ return isSecretName(decodeSafe(name)) || isSecretValue(decoded) ? `${name}=${hide()}` : part;
4055
+ }).join("");
4056
+ }
4057
+ function hidePath(path19, count) {
4058
+ const hide = hider(count);
4059
+ return path19.split("/").map((segment) => {
4060
+ const [own = "", ...params] = segment.split(";");
4061
+ const decoded = decodeSafe(own);
4062
+ const kept = decoded !== HIDDEN_VALUE && isSecretValue(decoded) ? hide() : own;
4063
+ return params.length ? `${kept};${hideParams(params.join(";"), count)}` : kept;
4064
+ }).join("/");
4065
+ }
4066
+ function hideSecretsInUrl(url, count = { n: 0 }) {
4067
+ const parts = URL_PARTS.exec(url);
4068
+ if (!parts) return url;
4069
+ const [, scheme = "", authority, path19 = "", query = "", fragment = ""] = parts;
4070
+ let out = "";
4071
+ if (authority !== void 0) {
4072
+ const at = authority.lastIndexOf("@");
4073
+ const colon = at >= 0 ? authority.slice(0, at).indexOf(":") : -1;
4074
+ out += colon >= 0 && colon < at - 1 ? `${scheme}//${authority.slice(0, colon + 1)}${hider(count)()}${authority.slice(at)}` : `${scheme}//${authority}`;
4075
+ }
4076
+ out += hidePath(path19, count);
4077
+ if (query) out += `?${hideParams(query.slice(1), count)}`;
4078
+ if (fragment) {
4079
+ const body = fragment.slice(1);
4080
+ const ask = body.indexOf("?");
4081
+ out += `#${ask >= 0 ? `${hidePath(body.slice(0, ask), count)}?${hideParams(body.slice(ask + 1), count)}` : body.includes("=") ? hideParams(body, count) : hidePath(body, count)}`;
4082
+ }
4083
+ return out;
4084
+ }
4085
+ var QUERY_PAIR = /([?&;#])([^=&#?;\s"'<>]{1,256})=([^&;#\s"'<>]*)/g;
4086
+ var URL_PASSWORD = /(\/\/[^/:@\s"'<>]{1,256}:)([^@/\s"'<>]{1,256})(@)/g;
4087
+ function hidePem(text, hide) {
4088
+ let out = "";
4089
+ let last = 0;
4090
+ let nextEnd = -2;
4091
+ PEM_BEGIN.lastIndex = 0;
4092
+ for (let begin = PEM_BEGIN.exec(text); begin; begin = PEM_BEGIN.exec(text)) {
4093
+ if (begin.index < last) continue;
4094
+ if (nextEnd !== -1 && nextEnd < begin.index) nextEnd = text.indexOf("-----END ", begin.index);
4095
+ const footer = nextEnd >= 0 ? /^-----END [A-Z0-9 ]{0,40}-----/.exec(text.slice(nextEnd, nextEnd + 60)) : null;
4096
+ const until = footer ? nextEnd + footer[0].length : begin.index + begin[0].length + (/^(?:\s*[A-Za-z0-9+/=]+)*/.exec(text.slice(begin.index + begin[0].length))?.[0].length ?? 0);
4097
+ out += `${text.slice(last, begin.index)}${hide()}`;
4098
+ last = until;
4099
+ PEM_BEGIN.lastIndex = until;
4100
+ }
4101
+ return out + text.slice(last);
4102
+ }
4103
+ function hideInText(text, count) {
4104
+ if (text.length < 4 || !/[A-Za-z0-9]/.test(text)) return text;
4105
+ const hide = hider(count);
4106
+ let out = hidePem(text, hide);
4107
+ out = out.replace(QUERY_PAIR, (all, sep8, name, value) => {
4108
+ const decoded = decodeSafe(value);
4109
+ if (!value || decoded === HIDDEN_VALUE) return all;
4110
+ return isSecretName(name) || isSecretValue(decoded) ? `${sep8}${name}=${hide()}` : all;
4111
+ });
4112
+ out = out.replace(URL_PASSWORD, (_all, before, _password, at) => `${before}${hide()}${at}`);
4113
+ out = out.replace(SET_COOKIE, (_all, before) => `${before}${hide()}`);
4114
+ out = out.replace(COOKIE_LINE, (_all, before, pairs) => {
4115
+ const values = pairs.replace(
4116
+ /([^=;\s]{1,256}=)([^;]*)/g,
4117
+ (pair, name, value) => value.trim() && value.trim() !== HIDDEN_VALUE ? `${name}${hide()}` : pair
4118
+ );
4119
+ return `${before}${values}`;
4120
+ });
4121
+ out = out.replace(
4122
+ JSON_FIELD,
4123
+ (all, before, name, value) => isSecretName(name) && value !== HIDDEN_VALUE ? `${before}${hide()}"` : all
4124
+ );
4125
+ out = hideSecretShapes(
4126
+ out.replace(BASIC, (all, encoded) => isBasicCredential(encoded) ? hide() : all),
4127
+ count
4128
+ );
4129
+ return out.replace(
4130
+ TOKEN_RUN,
4131
+ (run) => run.includes("/") && !/[+=]/.test(run) ? run.split("/").map((part) => looksRandom(part) ? hide() : part).join("/") : looksRandom(run) ? hide() : run
4132
+ );
4133
+ }
4134
+ function hideSecretsInText(text, count = { n: 0 }) {
4135
+ let out = "";
4136
+ let last = 0;
4137
+ for (const url of text.matchAll(URL_IN_TEXT)) {
4138
+ out += hideInText(text.slice(last, url.index), count) + hideSecretsInUrl(url[0], count);
4139
+ last = url.index + url[0].length;
4140
+ }
4141
+ return out + hideInText(text.slice(last), count);
4142
+ }
4143
+ var TYPED_TITLE = /^(?:Fill|Type|Insert) "/;
4144
+ function hideTypedText(title) {
4145
+ const typing = TYPED_TITLE.exec(title);
4146
+ if (!typing) return title;
4147
+ const start = typing[0].length;
4148
+ const end = title.endsWith('"') ? title.length - 1 : title.lastIndexOf('" ');
4149
+ return end >= start ? `${title.slice(0, start)}${HIDDEN_VALUE}${title.slice(end)}` : `${typing[0]}${HIDDEN_VALUE}"`;
4150
+ }
4151
+ var SECRET_FIELD_WORDS = /* @__PURE__ */ new Set([
4152
+ "passe",
4153
+ "mdp",
4154
+ "passwort",
4155
+ "kennwort",
4156
+ "contrasena",
4157
+ "clave",
4158
+ "senha",
4159
+ "cvv",
4160
+ "cvc",
4161
+ "csc",
4162
+ "pin",
4163
+ "pw",
4164
+ "totp",
4165
+ "mfa",
4166
+ "2fa"
4167
+ ]);
4168
+ var SECRET_STEMS = ["password", "passwd", "passwort", "kennwort", "contrasena", "senha", "motdepasse"];
4169
+ var SECRET_CODE_KINDS = /* @__PURE__ */ new Set([
4170
+ "verification",
4171
+ "security",
4172
+ "confirmation",
4173
+ "auth",
4174
+ "authentication",
4175
+ "access",
4176
+ "time",
4177
+ "otp",
4178
+ "sms",
4179
+ "login",
4180
+ "mfa",
4181
+ "2fa"
4182
+ ]);
4183
+ function isSecretLocator(locator) {
4184
+ const plain = locator.normalize("NFD").replace(/[̀-ͯ]/g, "");
4185
+ if (/type\s*=\s*["']?password\b/i.test(plain)) return true;
4186
+ for (const quoted of plain.matchAll(/(['"])((?:(?!\1)[^\\]|\\.)*)\1/g)) if (isSecretName(quoted[2])) return true;
4187
+ const words = nameWords(plain);
4188
+ return words.some(
4189
+ (word) => SECRET_WORDS.has(word) || SECRET_FIELD_WORDS.has(word) || SECRET_STEMS.some((stem) => word.includes(stem))
4190
+ ) || words.includes("code") && words.some((word) => SECRET_CODE_KINDS.has(word));
4191
+ }
4192
+ var TYPED_CALL = (
4193
+ // eslint-disable-next-line no-control-regex -- matches the ESC byte of a color code
4194
+ /^((?:\u001b\[[\d;]*m)*[ \t]*(?:(?:-|\d+ ×)[ \t]+)?(?:\w+\.)?)(fill|type|insertText)\("/gm
4195
+ );
4196
+ var TYPED_END = /"\)(?=(?:\u001b\[[\d;]*m|[ \t])*(?:\r?\n|$))/g;
4197
+ function hideTypedTextInLog(text) {
4198
+ let out = "";
4199
+ let from = 0;
4200
+ TYPED_CALL.lastIndex = 0;
4201
+ for (let call = TYPED_CALL.exec(text); call; call = TYPED_CALL.exec(text)) {
4202
+ out += `${text.slice(from, call.index)}${call[1]}${call[2]}("${HIDDEN_VALUE}")`;
4203
+ TYPED_END.lastIndex = call.index + call[0].length;
4204
+ const end = TYPED_END.exec(text);
4205
+ if (!end) return out;
4206
+ from = end.index + 2;
4207
+ TYPED_CALL.lastIndex = from;
4208
+ }
4209
+ return out + text.slice(from);
4210
+ }
4211
+ var READ_LOCATOR = /(?:waiting for|Locator:)[ \t]+(.*)$/gm;
4212
+ var RESOLVED_PASSWORD = /resolved to <input\b[^>\n]*\btype="password"/i;
4213
+ var READ_VALUE = (
4214
+ // eslint-disable-next-line no-control-regex -- matches the ESC byte of a color code
4215
+ /(unexpected value |(?:Expected|Received)(?: string)?:[ \t]*(?:\u001b\[[\d;]*m)*(?:not[ \t]+)?)"(?:.*"|.*)/g
4216
+ );
4217
+ var RESOLVED_ELEMENT = /resolved to <[^>\n]*/g;
4218
+ var VALUE_ATTRIBUTE = /\bvalue="[^"\n]*"/g;
4219
+ var COLOR = /\u001b\[[\d;]*m/g;
4220
+ function namesSecretField(text) {
4221
+ if (RESOLVED_PASSWORD.test(text)) return true;
4222
+ for (const named of text.matchAll(READ_LOCATOR))
4223
+ if (isSecretLocator(named[1].replace(COLOR, "").trim())) return true;
4224
+ return false;
4225
+ }
4226
+ function hideReadValues(text) {
4227
+ return text.replace(READ_VALUE, (_, before) => `${before}"${HIDDEN_VALUE}"`);
4228
+ }
4229
+ function hideResolvedValues(text, secretField) {
4230
+ if (!text.includes("resolved to <")) return text;
4231
+ return text.replace(
4232
+ RESOLVED_ELEMENT,
4233
+ (element) => secretField || /\btype="password"/i.test(element) ? element.replace(VALUE_ATTRIBUTE, `value="${HIDDEN_VALUE}"`) : element
4234
+ );
4235
+ }
4236
+ var LOGGED_HEADER = (
4237
+ // eslint-disable-next-line no-control-regex -- matches the ESC byte of a color code
4238
+ /^(?:\u001b\[[\d;]*m)*(?:[ \t]+(?:(?:-|\d+ ×)[ \t]+)?|(?:-|\d+ ×)[ \t]+)([A-Za-z][\w-]*): /
4239
+ );
4240
+ function colorsAtEnd(line) {
4241
+ let end = line.length;
4242
+ while (end > 0 && line[end - 1] === "m") {
4243
+ const start = line.lastIndexOf("\x1B[", end - 1);
4244
+ if (start < 0 || !/^[\d;]*$/.test(line.slice(start + 2, end - 1))) break;
4245
+ end = start;
4246
+ }
4247
+ return end;
4248
+ }
4249
+ function hideSecretHeaders(text) {
4250
+ if (!text.includes(": ")) return text;
4251
+ return text.split("\n").map((line) => {
4252
+ const header = LOGGED_HEADER.exec(line);
4253
+ if (!header || !isSecretName(header[1])) return line;
4254
+ const rest = line.slice(header[0].length);
4255
+ const end = colorsAtEnd(rest);
4256
+ return end === 0 ? line : `${header[0]}${HIDDEN_VALUE}${rest.slice(end)}`;
4257
+ }).join("\n");
4258
+ }
4259
+ function hideSecretsInLog(text, secretField = false) {
4260
+ const secret = secretField || namesSecretField(text);
4261
+ let hidden2 = hideResolvedValues(hideTypedTextInLog(text), secret);
4262
+ if (secret) hidden2 = hideReadValues(hidden2);
4263
+ return hideSecretHeaders(hidden2);
4264
+ }
4265
+ var CALL_LOG = "\nCall log:";
4266
+ var CALL_LOG_END = /\n(?:---\n|[ \t]+at )/g;
4267
+ function hideSecretsInError(text) {
4268
+ const secretField = namesSecretField(text);
4269
+ let out = "";
4270
+ let from = 0;
4271
+ for (; ; ) {
4272
+ const log = text.indexOf(CALL_LOG, from);
4273
+ const message = text.slice(from, log === -1 ? text.length : log);
4274
+ out += secretField ? hideReadValues(message) : message;
4275
+ if (log === -1) return hideSecretShapes(out);
4276
+ const start = log + CALL_LOG.length;
4277
+ CALL_LOG_END.lastIndex = start;
4278
+ const end = CALL_LOG_END.exec(text)?.index ?? text.length;
4279
+ out += CALL_LOG + hideSecretsInLog(text.slice(start, end), secretField);
4280
+ from = end;
4281
+ }
4282
+ }
4283
+
4284
+ // ../core/src/error-text.ts
4285
+ function joinErrorMessages(errors) {
4286
+ if (!errors || errors.length === 0) return null;
4287
+ const seen = /* @__PURE__ */ new Set();
4288
+ const parts = [];
4289
+ for (const err of errors) {
4290
+ const msg = err.message || err.value || "";
4291
+ if (!msg) continue;
4292
+ const dedupeKey = msg.trim().slice(0, 200);
4293
+ if (seen.has(dedupeKey)) continue;
4294
+ seen.add(dedupeKey);
4295
+ parts.push(hideSecretsInError(msg));
4296
+ }
4297
+ return parts.join("\n---\n") || null;
4298
+ }
4299
+
4300
+ // ../core/src/coverage.ts
4301
+ var MAX_COVERAGE_FILES = 2e3;
4302
+ var MAX_COVERAGE_RANGES = 1e4;
4303
+ var MAX_LINE = 1e6;
4304
+ var MAX_PATH_LENGTH = 500;
4305
+ var BLOB_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
4306
+ function isRecord(value) {
4307
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4308
+ }
4309
+ function isRuntime(value) {
4310
+ return value === "browser" || value === "server";
4311
+ }
4312
+ function isLine(value) {
4313
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= MAX_LINE;
4314
+ }
4315
+ function validRanges(raw) {
4316
+ if (!Array.isArray(raw)) return [];
4317
+ const out = [];
4318
+ for (const item of raw) {
4319
+ if (!Array.isArray(item) || item.length !== 2) continue;
4320
+ const [start, end] = item;
4321
+ if (isLine(start) && isLine(end) && start <= end) out.push([start, end]);
4322
+ }
4323
+ return out.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
4324
+ }
4325
+ function normalizeLineRanges(ranges) {
4326
+ const out = [];
4327
+ for (const range of validRanges(ranges)) {
4328
+ const last = out[out.length - 1];
4329
+ if (last && range[0] <= last[1] + 1) last[1] = Math.max(last[1], range[1]);
4330
+ else out.push(range);
4331
+ }
4332
+ return out;
4333
+ }
4334
+ function normalizeFunctionRanges(ranges) {
4335
+ const out = [];
4336
+ for (const range of validRanges(ranges)) {
4337
+ const last = out[out.length - 1];
4338
+ if (!last || last[0] !== range[0] || last[1] !== range[1]) out.push(range);
4339
+ }
4340
+ return out;
4341
+ }
4342
+ function normalizeCoveragePath(raw) {
4343
+ if (typeof raw !== "string" || raw.length > MAX_PATH_LENGTH || raw.includes("\0")) return null;
4344
+ const path19 = raw.replace(/\\/g, "/").replace(/^\.\//, "");
4345
+ if (!path19 || path19.startsWith("../") || path19.startsWith("/") || /^[A-Za-z]:\//.test(path19)) return null;
4346
+ if (/(^|\/)node_modules\//.test(path19)) return null;
4347
+ return path19;
4348
+ }
4349
+ function fileEntry(path19, runtime, blob, functions = [], lines = []) {
4350
+ const file = { path: path19, runtime };
4351
+ if (blob && (functions.length > 0 || lines.length > 0)) file.blob = blob;
4352
+ if (functions.length > 0) file.functions = functions;
4353
+ if (lines.length > 0) file.lines = lines;
4354
+ return file;
4355
+ }
4356
+ function captureOf(files, incomplete) {
4357
+ return incomplete ? { v: 1, files, incomplete: true } : { v: 1, files };
4358
+ }
4359
+ function compareFiles(a, b) {
4360
+ if (a.path !== b.path) return a.path < b.path ? -1 : 1;
3720
4361
  if (a.runtime !== b.runtime) return a.runtime < b.runtime ? -1 : 1;
3721
4362
  return 0;
3722
4363
  }
@@ -3725,11 +4366,11 @@ function sanitizeCoverage(raw) {
3725
4366
  const files = [];
3726
4367
  for (const item of raw.files) {
3727
4368
  if (!isRecord(item) || !isRuntime(item.runtime)) continue;
3728
- const path16 = normalizeCoveragePath(item.path);
3729
- if (path16 === null) continue;
4369
+ const path19 = normalizeCoveragePath(item.path);
4370
+ if (path19 === null) continue;
3730
4371
  const blob = typeof item.blob === "string" && BLOB_ID.test(item.blob) ? item.blob : void 0;
3731
4372
  files.push(
3732
- fileEntry(path16, item.runtime, blob, normalizeFunctionRanges(item.functions), normalizeLineRanges(item.lines))
4373
+ fileEntry(path19, item.runtime, blob, normalizeFunctionRanges(item.functions), normalizeLineRanges(item.lines))
3733
4374
  );
3734
4375
  }
3735
4376
  const merged = mergeCoverage(captureOf(files, raw.incomplete === true));
@@ -3930,6 +4571,14 @@ function decodeSourceMap(raw) {
3930
4571
  });
3931
4572
  return first;
3932
4573
  },
4574
+ forEachMapping(visit) {
4575
+ for (let line = 0; line < lineCount; line++) {
4576
+ for (let i = segments.lineStarts[line]; i < segments.lineStarts[line + 1]; i++) {
4577
+ const source = segments.sources[i];
4578
+ if (source >= 0) visit(line, segments.columns[i], source, segments.originalLines[i]);
4579
+ }
4580
+ }
4581
+ },
3933
4582
  originalLinesBetween(source, start, end, fromLine = 0) {
3934
4583
  let first = Number.POSITIVE_INFINITY;
3935
4584
  let last = -1;
@@ -4017,8 +4666,24 @@ function normalizeSourcePath(source) {
4017
4666
 
4018
4667
  // ../core/src/code-reach.ts
4019
4668
  var MAX_CODE_REACH_FILES = 2e3;
4020
- function scriptText(source) {
4021
- return { length: source.length, starts: Uint32Array.from(lineStarts(source)) };
4669
+ var isSpace = (ch) => ch === 32 || ch === 9 || ch === 13 || ch === 11 || ch === 12 || ch === 65279;
4670
+ function scriptText(source, options = {}) {
4671
+ const starts = Uint32Array.from(lineStarts(source));
4672
+ if (!options.code) return { length: source.length, starts };
4673
+ const codeStarts = new Int32Array(starts.length).fill(-1);
4674
+ const codeEnds = new Int32Array(starts.length).fill(-1);
4675
+ for (let line = 0; line < starts.length; line++) {
4676
+ const from = starts[line];
4677
+ let to = line + 1 < starts.length ? starts[line + 1] - 1 : source.length;
4678
+ let first = from;
4679
+ while (first < to && isSpace(source.charCodeAt(first))) first++;
4680
+ while (to > first && isSpace(source.charCodeAt(to - 1))) to--;
4681
+ if (first < to) {
4682
+ codeStarts[line] = first - from;
4683
+ codeEnds[line] = to - from;
4684
+ }
4685
+ }
4686
+ return { length: source.length, starts, code: { starts: codeStarts, ends: codeEnds } };
4022
4687
  }
4023
4688
  var textOf = (entry, text) => text ?? (entry.source === void 0 ? void 0 : scriptText(entry.source));
4024
4689
  function executedFunctionRanges(entry, length, all = false) {
@@ -4069,300 +4734,132 @@ function functionLines(entry, map, text, all) {
4069
4734
  const lines = map.originalLinesBetween(at.source, start, end, header);
4070
4735
  if (lines) add2(at.source, [header + 1, lines[1] + 1]);
4071
4736
  }
4072
- return out;
4073
- }
4074
- function finalizeCodeReach(files) {
4075
- const out = /* @__PURE__ */ new Set();
4076
- for (const raw of files) {
4077
- const file = normalizeCoveragePath(raw);
4078
- if (file !== null) out.add(file);
4079
- }
4080
- return [...out].sort().slice(0, MAX_CODE_REACH_FILES);
4081
- }
4082
-
4083
- // ../core/src/mask.ts
4084
- var DATA_URI_RE = /\bdata:[a-z0-9.+-]+\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/gi;
4085
- var JWT_RE = /\beyJ[\w-]{10,}\.[\w-]{5,}\.[\w-]{5,}\b/g;
4086
- var LONG_HEX_RE2 = /\b[0-9a-f]{32,}\b/gi;
4087
- function maskTokenLike(text) {
4088
- return text.replace(DATA_URI_RE, "data:[masked]").replace(JWT_RE, "[masked-token]").replace(LONG_HEX_RE2, "[masked-hex]");
4089
- }
4090
- var CREDENTIAL_PARAM_RE = /token|code|secret|password|passwd|pwd|key|session|auth|sig|credential|assertion|nonce|otp|jwt/i;
4091
- function maskUrlFragment(hash) {
4092
- const body = hash.startsWith("#") ? hash.slice(1) : hash;
4093
- const query = body.indexOf("?");
4094
- const route = query >= 0 ? body.slice(0, query) : body.includes("=") ? "" : body;
4095
- const params = query >= 0 ? body.slice(query + 1) : body.includes("=") ? body : null;
4096
- const masked = params === null ? null : params.split("&").map((param) => {
4097
- const eq = param.indexOf("=");
4098
- if (eq < 0) return maskTokenLike(param);
4099
- const name = param.slice(0, eq);
4100
- const value = param.slice(eq + 1);
4101
- return `${name}=${value && CREDENTIAL_PARAM_RE.test(name) ? "[masked]" : maskTokenLike(value)}`;
4102
- }).join("&");
4103
- const out = maskTokenLike(route) + (masked === null ? "" : query >= 0 ? `?${masked}` : masked);
4104
- return hash.startsWith("#") ? `#${out}` : out;
4105
- }
4106
- var HIDDEN_VALUE = "<hidden>";
4107
- var SECRET_AUTOCOMPLETE = [
4108
- "current-password",
4109
- "new-password",
4110
- "one-time-code",
4111
- "cc-number",
4112
- "cc-csc"
4113
- ];
4114
- var SECRET_WORDS = /* @__PURE__ */ new Set([
4115
- "pass",
4116
- "password",
4117
- "passwd",
4118
- "passphrase",
4119
- "passcode",
4120
- "pwd",
4121
- "secret",
4122
- "secrets",
4123
- "token",
4124
- "tokens",
4125
- "jwt",
4126
- "bearer",
4127
- "sig",
4128
- "signature",
4129
- "key",
4130
- "keys",
4131
- "apikey",
4132
- "auth",
4133
- "oauth",
4134
- "authorization",
4135
- "session",
4136
- "sessionid",
4137
- "jsessionid",
4138
- "sid",
4139
- "cookie",
4140
- "cookies",
4141
- "credential",
4142
- "credentials",
4143
- "otp",
4144
- "refresh",
4145
- "csrf",
4146
- "xsrf"
4147
- ]);
4148
- var SECRET_NAMES = /* @__PURE__ */ new Set(["code", "pin"]);
4149
- function nameWords(name) {
4150
- return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
4151
- }
4152
- function isSecretName(name) {
4153
- let secret = namesRead.get(name);
4154
- if (secret === void 0) {
4155
- secret = SECRET_NAMES.has(name.trim().toLowerCase()) || nameWords(name).some((word) => SECRET_WORDS.has(word));
4156
- if (namesRead.size >= 1024) namesRead.clear();
4157
- namesRead.set(name, secret);
4158
- }
4159
- return secret;
4160
- }
4161
- var namesRead = /* @__PURE__ */ new Map();
4162
- var SECRET_SHAPES = [
4163
- /\beyJ[\w-]{5,}\.[\w-]{5,}\.[\w-]*/g,
4164
- /\bBearer(?:\s+|%20)[\w.~+/-]{8,}=*/gi,
4165
- /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{8,}/g,
4166
- /\bwhsec_[A-Za-z0-9]{20,}/g,
4167
- /\bsk-(?=[\w-]{0,200}\d)(?=[\w-]{0,200}[A-Z])[\w-]{32,}/g,
4168
- /\bglpat-[\w-]{20,}/g,
4169
- /\bnpm_[A-Za-z0-9]{36}\b/g,
4170
- /\bSK[0-9a-f]{32}\b/g,
4171
- /\bAKIA[0-9A-Z]{16}\b/g,
4172
- /\bAIza[\w-]{30,}/g,
4173
- /\bgh[opsu]_[A-Za-z0-9]{20,}/g,
4174
- /\bgithub_pat_\w{20,}/g,
4175
- /\bxox[abprs]-[\w-]{8,}/g
4176
- ];
4177
- var WHOLE_SHAPES = SECRET_SHAPES.map(
4178
- (re) => new RegExp(`^(?:${re.source})$`, re.flags.replace("g", ""))
4179
- );
4180
- var BASIC = /\bBasic\s+([A-Za-z0-9+/]{4,}={0,2})(?![\w+/=])/g;
4181
- var PEM_BEGIN = /-----BEGIN ([A-Z0-9 ]{0,40}PRIVATE KEY)-----/g;
4182
- var SET_COOKIE = /(\bSet-Cookie:[ \t]*[^=;\s]{1,256}=)([^;\r\n]{1,4096})/gi;
4183
- var COOKIE_LINE = /((?<![\w-])Cookie:[ \t]*)([^\r\n]{1,16384})/gi;
4184
- var JSON_FIELD = /("((?:[^"\\\r\n]|\\.){1,256})"\s*:\s*")((?:[^"\\\r\n]|\\.){1,4096})"/g;
4185
- var TOKEN_RUN = /[A-Za-z0-9+/_-]{40,}={0,2}/g;
4186
- var MIN_RANDOM = 40;
4187
- var BASE64_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
4188
- function base64OfText(run) {
4189
- let bits = 0;
4190
- let acc = 0;
4191
- let bytes = 0;
4192
- let printable = 0;
4193
- for (const c of run.replace(/=+$/, "")) {
4194
- const digit = BASE64_DIGITS.indexOf(c === "-" ? "+" : c === "_" ? "/" : c);
4195
- if (digit < 0) return false;
4196
- acc = (acc << 6 | digit) & 65535;
4197
- bits += 6;
4198
- if (bits < 8) continue;
4199
- bits -= 8;
4200
- const byte = acc >> bits & 255;
4201
- bytes++;
4202
- if (byte >= 32 && byte < 127 || byte === 9 || byte === 10 || byte === 13) printable++;
4203
- }
4204
- return bytes > 0 && printable * 10 >= bytes * 9;
4205
- }
4206
- function bitsPerChar(text) {
4207
- const counts = /* @__PURE__ */ new Map();
4208
- for (const c of text) counts.set(c, (counts.get(c) ?? 0) + 1);
4209
- let bits = 0;
4210
- for (const n of counts.values()) bits -= n / text.length * Math.log2(n / text.length);
4211
- return bits;
4212
- }
4213
- function looksRandom(text) {
4214
- if (text.length < MIN_RANDOM || !/[A-Z]/.test(text) || !/[a-z]/.test(text) || !/\d/.test(text)) return false;
4215
- let letters = 0;
4216
- for (const c of text) if (c >= "a" && c <= "z" || c >= "A" && c <= "Z") letters++;
4217
- let wordy = 0;
4218
- for (const run of text.matchAll(/[a-z]{6,}|[A-Z]{6,}/g)) wordy += run[0].length;
4219
- return wordy * 5 <= letters && bitsPerChar(text) >= 4 && !base64OfText(text);
4220
- }
4221
- function isBasicCredential(encoded) {
4222
- const text = encoded.replace(/=+$/, "");
4223
- if (text.length % 4 === 1) return false;
4224
- let decoded = "";
4225
- let bits = 0;
4226
- let acc = 0;
4227
- for (const c of text) {
4228
- const digit = BASE64_DIGITS.indexOf(c);
4229
- if (digit < 0) return false;
4230
- acc = (acc << 6 | digit) & 65535;
4231
- bits += 6;
4232
- if (bits < 8) continue;
4233
- bits -= 8;
4234
- decoded += String.fromCharCode(acc >> bits & 255);
4235
- }
4236
- return /^[\x20-\x7e]+:[\x20-\x7e]*$/.test(decoded);
4237
- }
4238
- function isSecretValue(value) {
4239
- const text = value.trim();
4240
- if (text.length < 10 || text.length > 4096) return false;
4241
- if (WHOLE_SHAPES.some((re) => re.test(text))) return true;
4242
- const basic = /^Basic\s+([A-Za-z0-9+/]{4,}={0,2})$/.exec(text);
4243
- if (basic && isBasicCredential(basic[1])) return true;
4244
- if (/^-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY-----/.test(text)) return true;
4245
- return /^[A-Za-z0-9+/_-]{40,}={0,2}$/.test(text) && looksRandom(text);
4246
- }
4247
- var URL_IN_TEXT = /\b[a-z][a-z0-9+.-]{0,31}:\/\/[^\s"'<>`]+/gi;
4248
- var URL_PARTS = /^(?:([a-z][a-z0-9+.-]*:)?\/\/([^/?#]*))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?$/i;
4249
- function decodeSafe(text) {
4250
- try {
4251
- return decodeURIComponent(text);
4252
- } catch {
4253
- return text;
4254
- }
4255
- }
4256
- function hider(count) {
4257
- return () => {
4258
- count.n++;
4259
- return HIDDEN_VALUE;
4260
- };
4737
+ return out;
4261
4738
  }
4262
- function hideParams(params, count) {
4263
- const hide = hider(count);
4264
- return params.split(/([&;])/).map((part, i) => {
4265
- const eq = part.indexOf("=");
4266
- if (i % 2 === 1 || eq < 0) return part;
4267
- const name = part.slice(0, eq);
4268
- const value = part.slice(eq + 1);
4269
- const decoded = decodeSafe(value);
4270
- if (!value || decoded === HIDDEN_VALUE) return part;
4271
- return isSecretName(decodeSafe(name)) || isSecretValue(decoded) ? `${name}=${hide()}` : part;
4272
- }).join("");
4739
+ function finalizeCodeReach(files) {
4740
+ const out = /* @__PURE__ */ new Set();
4741
+ for (const raw of files) {
4742
+ const file = normalizeCoveragePath(raw);
4743
+ if (file !== null) out.add(file);
4744
+ }
4745
+ return [...out].sort().slice(0, MAX_CODE_REACH_FILES);
4273
4746
  }
4274
- function hidePath(path16, count) {
4275
- const hide = hider(count);
4276
- return path16.split("/").map((segment) => {
4277
- const [own = "", ...params] = segment.split(";");
4278
- const decoded = decodeSafe(own);
4279
- const kept = decoded !== HIDDEN_VALUE && isSecretValue(decoded) ? hide() : own;
4280
- return params.length ? `${kept};${hideParams(params.join(";"), count)}` : kept;
4281
- }).join("/");
4747
+ function executedOffsets(functions) {
4748
+ const ranges = [];
4749
+ for (const fn of functions)
4750
+ for (const range of fn.ranges) if (range.endOffset > range.startOffset) ranges.push(range);
4751
+ ranges.sort((a, b) => a.startOffset - b.startOffset || b.endOffset - a.endOffset);
4752
+ const out = [];
4753
+ const emit = (from, to, count) => {
4754
+ if (to <= from || count <= 0) return;
4755
+ const last = out[out.length - 1];
4756
+ if (last && from <= last[1]) last[1] = Math.max(last[1], to);
4757
+ else out.push([from, to]);
4758
+ };
4759
+ const open = [];
4760
+ let at = 0;
4761
+ const close = (until) => {
4762
+ while (open.length > 0 && open[open.length - 1].endOffset <= until) {
4763
+ const top = open.pop();
4764
+ emit(at, top.endOffset, top.count);
4765
+ at = Math.max(at, top.endOffset);
4766
+ }
4767
+ };
4768
+ for (const range of ranges) {
4769
+ close(range.startOffset);
4770
+ const parent = open[open.length - 1];
4771
+ const end = parent ? Math.min(range.endOffset, parent.endOffset) : range.endOffset;
4772
+ if (parent) emit(at, range.startOffset, parent.count);
4773
+ at = Math.max(at, range.startOffset);
4774
+ open.push(end === range.endOffset ? range : { ...range, endOffset: end });
4775
+ }
4776
+ close(Number.POSITIVE_INFINITY);
4777
+ return out;
4282
4778
  }
4283
- function hideSecretsInUrl(url, count = { n: 0 }) {
4284
- const parts = URL_PARTS.exec(url);
4285
- if (!parts) return url;
4286
- const [, scheme = "", authority, path16 = "", query = "", fragment = ""] = parts;
4287
- let out = "";
4288
- if (authority !== void 0) {
4289
- const at = authority.lastIndexOf("@");
4290
- const colon = at >= 0 ? authority.slice(0, at).indexOf(":") : -1;
4291
- out += colon >= 0 && colon < at - 1 ? `${scheme}//${authority.slice(0, colon + 1)}${hider(count)()}${authority.slice(at)}` : `${scheme}//${authority}`;
4292
- }
4293
- out += hidePath(path16, count);
4294
- if (query) out += `?${hideParams(query.slice(1), count)}`;
4295
- if (fragment) {
4296
- const body = fragment.slice(1);
4297
- const ask = body.indexOf("?");
4298
- out += `#${ask >= 0 ? `${hidePath(body.slice(0, ask), count)}?${hideParams(body.slice(ask + 1), count)}` : body.includes("=") ? hideParams(body, count) : hidePath(body, count)}`;
4779
+ function unionOffsets(a, b) {
4780
+ const all = [...a, ...b].sort((x, y) => x[0] - y[0] || x[1] - y[1]);
4781
+ const out = [];
4782
+ for (const [start, end] of all) {
4783
+ const last = out[out.length - 1];
4784
+ if (last && start <= last[1]) last[1] = Math.max(last[1], end);
4785
+ else out.push([start, end]);
4299
4786
  }
4300
4787
  return out;
4301
4788
  }
4302
- var QUERY_PAIR = /([?&;#])([^=&#?;\s"'<>]{1,256})=([^&;#\s"'<>]*)/g;
4303
- var URL_PASSWORD = /(\/\/[^/:@\s"'<>]{1,256}:)([^@/\s"'<>]{1,256})(@)/g;
4304
- function hidePem(text, hide) {
4305
- let out = "";
4306
- let last = 0;
4307
- let nextEnd = -2;
4308
- PEM_BEGIN.lastIndex = 0;
4309
- for (let begin = PEM_BEGIN.exec(text); begin; begin = PEM_BEGIN.exec(text)) {
4310
- if (begin.index < last) continue;
4311
- if (nextEnd !== -1 && nextEnd < begin.index) nextEnd = text.indexOf("-----END ", begin.index);
4312
- const footer = nextEnd >= 0 ? /^-----END [A-Z0-9 ]{0,40}-----/.exec(text.slice(nextEnd, nextEnd + 60)) : null;
4313
- const until = footer ? nextEnd + footer[0].length : begin.index + begin[0].length + (/^(?:\s*[A-Za-z0-9+/=]+)*/.exec(text.slice(begin.index + begin[0].length))?.[0].length ?? 0);
4314
- out += `${text.slice(last, begin.index)}${hide()}`;
4315
- last = until;
4316
- PEM_BEGIN.lastIndex = until;
4789
+ function ranBetween(executed, from, to) {
4790
+ let low = 0;
4791
+ let high = executed.length - 1;
4792
+ while (low <= high) {
4793
+ const mid = low + high >> 1;
4794
+ const [start, end] = executed[mid];
4795
+ if (end <= from) low = mid + 1;
4796
+ else if (start >= to) high = mid - 1;
4797
+ else return true;
4317
4798
  }
4318
- return out + text.slice(last);
4799
+ return false;
4319
4800
  }
4320
- function hideInText(text, count) {
4321
- if (text.length < 4 || !/[A-Za-z0-9]/.test(text)) return text;
4322
- const hide = hider(count);
4323
- let out = hidePem(text, hide);
4324
- out = out.replace(QUERY_PAIR, (all, sep7, name, value) => {
4325
- const decoded = decodeSafe(value);
4326
- if (!value || decoded === HIDDEN_VALUE) return all;
4327
- return isSecretName(name) || isSecretValue(decoded) ? `${sep7}${name}=${hide()}` : all;
4328
- });
4329
- out = out.replace(URL_PASSWORD, (_all, before, _password, at) => `${before}${hide()}${at}`);
4330
- out = out.replace(SET_COOKIE, (_all, before) => `${before}${hide()}`);
4331
- out = out.replace(COOKIE_LINE, (_all, before, pairs) => {
4332
- const values = pairs.replace(
4333
- /([^=;\s]{1,256}=)([^;]*)/g,
4334
- (pair, name, value) => value.trim() && value.trim() !== HIDDEN_VALUE ? `${name}${hide()}` : pair
4335
- );
4336
- return `${before}${values}`;
4337
- });
4338
- out = out.replace(
4339
- JSON_FIELD,
4340
- (all, before, name, value) => isSecretName(name) && value !== HIDDEN_VALUE ? `${before}${hide()}"` : all
4341
- );
4342
- out = out.replace(BASIC, (all, encoded) => isBasicCredential(encoded) ? hide() : all);
4343
- for (const shape of SECRET_SHAPES) out = out.replace(shape, () => hide());
4344
- return out.replace(
4345
- TOKEN_RUN,
4346
- (run) => run.includes("/") && !/[+=]/.test(run) ? run.split("/").map((part) => looksRandom(part) ? hide() : part).join("/") : looksRandom(run) ? hide() : run
4347
- );
4801
+ function toLineRanges(lines) {
4802
+ const sorted = [...lines].sort((a, b) => a - b);
4803
+ const out = [];
4804
+ for (const line of sorted) {
4805
+ const last = out[out.length - 1];
4806
+ if (last && line + 1 <= last[1] + 1) last[1] = Math.max(last[1], line + 1);
4807
+ else out.push([line + 1, line + 1]);
4808
+ }
4809
+ return out;
4348
4810
  }
4349
- function hideSecretsInText(text, count = { n: 0 }) {
4350
- let out = "";
4351
- let last = 0;
4352
- for (const url of text.matchAll(URL_IN_TEXT)) {
4353
- out += hideInText(text.slice(last, url.index), count) + hideSecretsInUrl(url[0], count);
4354
- last = url.index + url[0].length;
4811
+ function scriptLines(entry, executed, map, text) {
4812
+ const out = /* @__PURE__ */ new Map();
4813
+ const read = textOf(entry, text);
4814
+ if (!read) return out;
4815
+ const starts = read.starts;
4816
+ if (map) {
4817
+ const executable2 = /* @__PURE__ */ new Map();
4818
+ const ran2 = /* @__PURE__ */ new Map();
4819
+ const add2 = (into, source, line) => {
4820
+ let set = into.get(source);
4821
+ if (!set) into.set(source, set = /* @__PURE__ */ new Set());
4822
+ set.add(line);
4823
+ };
4824
+ map.forEachMapping((line, column, source, originalLine) => {
4825
+ if (line >= starts.length || originalLine < 0) return;
4826
+ add2(executable2, source, originalLine);
4827
+ const offset = starts[line] + column;
4828
+ if (offset < read.length && ranBetween(executed, offset, offset + 1)) add2(ran2, source, originalLine);
4829
+ });
4830
+ for (const [source, lines] of executable2) {
4831
+ out.set(source, { executable: toLineRanges(lines), lines: toLineRanges(ran2.get(source) ?? []) });
4832
+ }
4833
+ return out;
4355
4834
  }
4356
- return out + hideInText(text.slice(last), count);
4835
+ const code = read.code ?? (entry.source !== void 0 ? scriptText(entry.source, { code: true }).code : void 0);
4836
+ if (!code) return out;
4837
+ const executable = /* @__PURE__ */ new Map();
4838
+ for (const range of executedFunctionRanges(entry, read.length, true)) {
4839
+ const first = offsetToPosition(starts, range.start).line;
4840
+ const last = offsetToPosition(starts, Math.max(range.start, range.end - 1)).line;
4841
+ for (let line = first; line <= last; line++) {
4842
+ if (code.starts[line] < 0) continue;
4843
+ const from = Math.max(starts[line] + code.starts[line], range.start);
4844
+ const to = Math.min(starts[line] + code.ends[line], range.end);
4845
+ if (from >= to) continue;
4846
+ const parts = executable.get(line);
4847
+ if (parts) parts.push([from, to]);
4848
+ else executable.set(line, [[from, to]]);
4849
+ }
4850
+ }
4851
+ const ran = [];
4852
+ for (const [line, parts] of executable) {
4853
+ if (parts.some(([from, to]) => ranBetween(executed, from, to))) ran.push(line);
4854
+ }
4855
+ if (executable.size > 0) out.set(-1, { executable: toLineRanges(executable.keys()), lines: toLineRanges(ran) });
4856
+ return out;
4357
4857
  }
4358
4858
 
4359
4859
  // src/internal/capture/inspect-on-failure.ts
4360
- function isCi(ci) {
4361
- return ci !== void 0 && ci !== "" && ci !== "false";
4362
- }
4363
4860
  function shouldInspectOnFailure(gate) {
4364
4861
  if (gate.enabled !== "true") return false;
4365
- if (isCi(gate.ci)) return false;
4862
+ if (gate.ci) return false;
4366
4863
  if (gate.headless !== false) return false;
4367
4864
  if (gate.status !== "failed" && gate.status !== "timedOut") return false;
4368
4865
  if (gate.status === gate.expectedStatus) return false;
@@ -4372,7 +4869,7 @@ function environmentalSkipReason(gate) {
4372
4869
  if (gate.enabled !== "true") return null;
4373
4870
  if (gate.status !== "failed" && gate.status !== "timedOut") return null;
4374
4871
  if (gate.status === gate.expectedStatus) return null;
4375
- if (isCi(gate.ci)) return "running under CI \u2014 this is a headed, local-only feature";
4872
+ if (gate.ci) return "running under CI \u2014 this is a headed, local-only feature";
4376
4873
  if (gate.headless !== false) {
4377
4874
  return "the browser is headless \u2014 re-run with --headed (or set use: { headless: false })";
4378
4875
  }
@@ -4382,7 +4879,7 @@ function inspectionGateFromTestInfo(testInfo, enabled = process.env.PIWI_INSPECT
4382
4879
  const use = testInfo.project?.use ?? {};
4383
4880
  return {
4384
4881
  enabled,
4385
- ci: process.env.CI,
4882
+ ci: detectCi(process.env),
4386
4883
  status: testInfo.status,
4387
4884
  expectedStatus: testInfo.expectedStatus,
4388
4885
  headless: use.headless,
@@ -4442,9 +4939,9 @@ function unlessEnded(run, ended) {
4442
4939
  if (!ended) return run;
4443
4940
  return Promise.race([
4444
4941
  run,
4445
- new Promise((resolve5) => {
4446
- if (ended.aborted) resolve5(void 0);
4447
- else ended.addEventListener("abort", () => resolve5(void 0), { once: true });
4942
+ new Promise((resolve6) => {
4943
+ if (ended.aborted) resolve6(void 0);
4944
+ else ended.addEventListener("abort", () => resolve6(void 0), { once: true });
4448
4945
  })
4449
4946
  ]);
4450
4947
  }
@@ -4590,6 +5087,7 @@ function applyPickToSnapshots(snapshots, pick) {
4590
5087
  }
4591
5088
 
4592
5089
  // src/internal/capture/pause-at.ts
5090
+ var fs6 = __toESM(require("fs"));
4593
5091
  var path8 = __toESM(require("path"));
4594
5092
 
4595
5093
  // ../core/src/editor-send.ts
@@ -4709,10 +5207,23 @@ function internalCall(owner, run) {
4709
5207
  return wrap.call(owner, run, { internal: true, title: "Piwi capture" });
4710
5208
  }
4711
5209
 
5210
+ // src/internal/support/playwright-version.ts
5211
+ function playwrightVersionAtLeast(version, minimum) {
5212
+ const have = version ? /^(\d+)\.(\d+)/.exec(version) : null;
5213
+ const want = /^(\d+)\.(\d+)/.exec(minimum);
5214
+ if (!have || !want) return false;
5215
+ const major = Number(have[1]);
5216
+ const wantMajor = Number(want[1]);
5217
+ return major > wantMajor || major === wantMajor && Number(have[2]) >= Number(want[2]);
5218
+ }
5219
+
4712
5220
  // src/internal/capture/pause-at.ts
5221
+ function lineKey(line, windows = process.platform === "win32") {
5222
+ return windows ? line.toLowerCase() : line;
5223
+ }
4713
5224
  var PauseSet = class {
4714
5225
  constructor(lines) {
4715
- this.lines = lines;
5226
+ this.lines = new Set([...lines].map((line) => lineKey(line)));
4716
5227
  }
4717
5228
  get size() {
4718
5229
  return this.lines.size;
@@ -4721,18 +5232,27 @@ var PauseSet = class {
4721
5232
  matches(callerLocation) {
4722
5233
  if (!callerLocation) return false;
4723
5234
  const col = callerLocation.lastIndexOf(":");
4724
- return col > 0 && this.lines.has(callerLocation.slice(0, col));
5235
+ return col > 0 && this.lines.has(lineKey(callerLocation.slice(0, col)));
4725
5236
  }
4726
5237
  };
4727
5238
  var NO_BREAKPOINTS = new PauseSet(/* @__PURE__ */ new Set());
4728
5239
  function callSiteFile(file, cwd) {
4729
5240
  const slashed = file.replace(/\\/g, "/");
4730
5241
  const absolute = path8.isAbsolute(file) || path8.isAbsolute(slashed) || /^[A-Za-z]:\//.test(slashed);
4731
- let rel = absolute ? path8.relative(cwd, file) : path8.normalize(slashed);
5242
+ const resolved = path8.resolve(cwd, absolute ? file : slashed);
5243
+ const real = realPath(resolved);
5244
+ let rel = real !== null && real !== resolved ? path8.relative(realPath(cwd) ?? cwd, real) : absolute ? path8.relative(cwd, file) : path8.normalize(slashed);
4732
5245
  rel = rel.split(path8.sep).join("/").replace(/\\/g, "/");
4733
5246
  if (rel.startsWith("./")) rel = rel.slice(2);
4734
5247
  return rel;
4735
5248
  }
5249
+ function realPath(file) {
5250
+ try {
5251
+ return fs6.realpathSync(file);
5252
+ } catch {
5253
+ return null;
5254
+ }
5255
+ }
4736
5256
  function stopCallSite(location, cwd = process.cwd()) {
4737
5257
  if (!location.line) return null;
4738
5258
  return `${callSiteFile(location.file, cwd)}:${location.line}:${location.column ?? 0}`;
@@ -4793,13 +5313,23 @@ function callSitePlace(callSite) {
4793
5313
  function placeLine(place, cwd = process.cwd()) {
4794
5314
  return `${callSiteFile(place.file, cwd)}:${place.line}`;
4795
5315
  }
4796
- function pauseGateFromTestInfo(testInfo) {
5316
+ function pauseGateFromTestInfo(testInfo, headless) {
4797
5317
  const use = testInfo.project?.use ?? {};
4798
5318
  const debug = testInfo._configInternal?.configCLIOverrides?.debug;
4799
- return { ci: process.env.CI, headless: use.headless, pwdebug: process.env.PWDEBUG, debug };
5319
+ return {
5320
+ ci: detectCi(process.env),
5321
+ headless: headless !== void 0 ? headless : use.headless,
5322
+ pwdebug: process.env.PWDEBUG,
5323
+ debug
5324
+ };
5325
+ }
5326
+ function mayPause(gate) {
5327
+ if (process.env.PIWI_PAUSE_AT) return true;
5328
+ if (gate.pwdebug && !["0", "false", "console"].includes(gate.pwdebug)) return true;
5329
+ return typeof gate.debug === "string" && gate.debug.length > 0;
4800
5330
  }
4801
5331
  function pauseSkipReason(gate) {
4802
- if (isCi(gate.ci)) return "running under CI \u2014 breakpoints pause local runs only";
5332
+ if (gate.ci) return "running under CI \u2014 breakpoints pause local runs only";
4803
5333
  if (gate.headless !== false && !gate.channel)
4804
5334
  return "the browser is headless \u2014 re-run with --headed (or set use: { headless: false })";
4805
5335
  if (gate.pwdebug && !["0", "false", "console"].includes(gate.pwdebug))
@@ -4819,7 +5349,7 @@ function atBreakpoint(state, callSite) {
4819
5349
  }
4820
5350
  function atStop(state, callSite) {
4821
5351
  if (callSite) {
4822
- const reason = state.step ? "step" : state.pause ? "pause" : state.runTo !== null && callSiteLine(callSite) === state.runTo ? "run-to" : atBreakpoint(state, callSite) ? "breakpoint" : null;
5352
+ const reason = state.step ? "step" : state.pause ? "pause" : state.runTo !== null && lineKey(callSiteLine(callSite)) === lineKey(state.runTo) ? "run-to" : atBreakpoint(state, callSite) ? "breakpoint" : null;
4823
5353
  if (reason) {
4824
5354
  stopShown(state);
4825
5355
  return { show: reason };
@@ -4850,6 +5380,9 @@ function goOn(state, answer) {
4850
5380
  return wantsStops(state) ? "next" : "resume";
4851
5381
  }
4852
5382
  var ENDED_REASON = "Ended from Piwi";
5383
+ function takesEndSignal(version) {
5384
+ return playwrightVersionAtLeast(version, "1.62");
5385
+ }
4853
5386
  var OPTIONS_AT = {
4854
5387
  fill: 1,
4855
5388
  selectOption: 1,
@@ -4907,11 +5440,23 @@ function syncInspectorSwitch() {
4907
5440
  if (closed && process.env[NO_INSPECTOR_ENV] === void 0) {
4908
5441
  process.env[NO_INSPECTOR_ENV] = "1";
4909
5442
  inspectorSwitch.set = true;
5443
+ clearSwitchAtStop();
4910
5444
  } else if (!closed && inspectorSwitch.set) {
4911
- if (process.env[NO_INSPECTOR_ENV] === "1") delete process.env[NO_INSPECTOR_ENV];
4912
- inspectorSwitch.set = false;
5445
+ clearSwitch();
4913
5446
  }
4914
5447
  }
5448
+ function clearSwitch() {
5449
+ if (inspectorSwitch.set && process.env[NO_INSPECTOR_ENV] === "1") delete process.env[NO_INSPECTOR_ENV];
5450
+ inspectorSwitch.set = false;
5451
+ }
5452
+ var clearsAtStop = false;
5453
+ function clearSwitchAtStop() {
5454
+ if (clearsAtStop) return;
5455
+ clearsAtStop = true;
5456
+ process.prependListener("message", (message) => {
5457
+ if (message?.method === "__stop__") clearSwitch();
5458
+ });
5459
+ }
4915
5460
  function markPausesWrapped() {
4916
5461
  inspectorSwitch.wrapped = true;
4917
5462
  syncInspectorSwitch();
@@ -5019,9 +5564,9 @@ var BarIntents = class {
5019
5564
  /** Hand the bar an intent; false while it runs one, or holds one already. */
5020
5565
  offer(intent) {
5021
5566
  if (this.busy || this.queued) return false;
5022
- const take = this.take;
5567
+ const take2 = this.take;
5023
5568
  this.take = null;
5024
- if (take) take(intent);
5569
+ if (take2) take2(intent);
5025
5570
  else this.queued = intent;
5026
5571
  return true;
5027
5572
  }
@@ -5031,8 +5576,8 @@ var BarIntents = class {
5031
5576
  const queued = this.queued;
5032
5577
  this.queued = null;
5033
5578
  if (queued) return Promise.resolve(queued);
5034
- return new Promise((resolve5) => {
5035
- this.take = resolve5;
5579
+ return new Promise((resolve6) => {
5580
+ this.take = resolve6;
5036
5581
  });
5037
5582
  }
5038
5583
  /** The bar got its answer: it takes no intent until it waits again. */
@@ -5047,7 +5592,7 @@ async function within(run, ms) {
5047
5592
  try {
5048
5593
  return await Promise.race([
5049
5594
  run,
5050
- new Promise((resolve5) => timer = setTimeout(() => resolve5(void 0), ms))
5595
+ new Promise((resolve6) => timer = setTimeout(() => resolve6(void 0), ms))
5051
5596
  ]);
5052
5597
  } finally {
5053
5598
  clearTimeout(timer);
@@ -5080,13 +5625,68 @@ async function viewHere(page, probe, onPick, onRecord, ended, intents, onIntent,
5080
5625
  }
5081
5626
  }
5082
5627
  }
5628
+ var REDRAW_MS = 500;
5629
+ var stopHighlights = 0;
5630
+ var FRAME_HOP = " >> internal:control=enter-frame >> ";
5631
+ async function frameOf(locator) {
5632
+ const own = locator;
5633
+ if (!own._frame || typeof own._selector !== "string") return null;
5634
+ const at = own._selector.lastIndexOf(FRAME_HOP);
5635
+ if (at < 0) return { frame: own._frame, selector: own._selector };
5636
+ const [iframe] = await own._frame.locator(own._selector.slice(0, at)).first().elementHandles();
5637
+ if (!iframe) return null;
5638
+ try {
5639
+ const frame = await iframe.contentFrame();
5640
+ return frame ? { frame, selector: own._selector.slice(at + FRAME_HOP.length) } : null;
5641
+ } finally {
5642
+ await iframe.dispose().catch(() => void 0);
5643
+ }
5644
+ }
5645
+ function highlightAtStop(page, locator, what, label) {
5646
+ const id = `${what}-${++stopHighlights}`;
5647
+ const arg = { id, kind: what, label };
5648
+ const drawnIn = /* @__PURE__ */ new Set();
5649
+ let hidden2 = false;
5650
+ let timer;
5651
+ const draw = async () => {
5652
+ const target = await frameOf(locator);
5653
+ if (hidden2) return 0;
5654
+ if (!target) return locator.evaluateAll(showStopHighlight, arg);
5655
+ drawnIn.add(target.frame);
5656
+ return target.frame.locator(target.selector).evaluateAll(showStopHighlight, arg);
5657
+ };
5658
+ const again = () => {
5659
+ if (hidden2 || page.isClosed?.()) return;
5660
+ timer = setTimeout(
5661
+ () => void internalCall(page, draw).catch(() => 0).then(again),
5662
+ REDRAW_MS
5663
+ );
5664
+ timer.unref?.();
5665
+ };
5666
+ const first = internalCall(page, draw).catch(() => 0);
5667
+ void first.then(again);
5668
+ const removeIn = (frame) => internalCall(page, async () => frame.evaluate(removeStopHighlight, id)).catch(() => false);
5669
+ return {
5670
+ shown: first.then((boxes) => boxes > 0),
5671
+ hide: async () => {
5672
+ hidden2 = true;
5673
+ clearTimeout(timer);
5674
+ try {
5675
+ const frames = drawnIn.size ? [...drawnIn] : [page.mainFrame()];
5676
+ const removed = await within(Promise.all(frames.map(removeIn)), TAKE_DOWN_MS);
5677
+ return removed?.includes(true) ?? false;
5678
+ } catch {
5679
+ return false;
5680
+ }
5681
+ }
5682
+ };
5683
+ }
5083
5684
  async function pauseHere(page, point, probe, onPick, onRecord, ended, intents, onIntent) {
5084
- let shown2 = null;
5685
+ let highlight = null;
5085
5686
  try {
5086
- const highlight = point.target?.highlight;
5087
- if (typeof highlight === "function") {
5088
- const highlighted = Promise.resolve().then(() => highlight.call(point.target)).catch(() => null);
5089
- shown2 = await within(highlighted, HIGHLIGHT_MS) ?? null;
5687
+ if (point.target) {
5688
+ highlight = point.target.highlight();
5689
+ await within(highlight.shown, HIGHLIGHT_MS);
5090
5690
  }
5091
5691
  const arg = {
5092
5692
  place: pausePlace(point.location),
@@ -5145,17 +5745,10 @@ async function pauseHere(page, point, probe, onPick, onRecord, ended, intents, o
5145
5745
  } catch {
5146
5746
  return "resume";
5147
5747
  } finally {
5148
- const takeDown = async () => {
5149
- try {
5150
- if (ended?.aborted) await page.evaluate(takePauseState);
5151
- const dispose = shown2?.dispose;
5152
- const hide = page.hideHighlight;
5153
- if (typeof dispose === "function") await dispose.call(shown2);
5154
- else if (typeof hide === "function") await hide.call(page);
5155
- } catch {
5156
- }
5157
- };
5158
- await within(takeDown(), TAKE_DOWN_MS);
5748
+ await Promise.all([
5749
+ ended?.aborted ? within(page.evaluate(takePauseState), TAKE_DOWN_MS).catch(() => void 0) : void 0,
5750
+ highlight?.hide()
5751
+ ]);
5159
5752
  }
5160
5753
  }
5161
5754
 
@@ -5201,6 +5794,12 @@ function locatorOn(page, source) {
5201
5794
  }
5202
5795
  }
5203
5796
 
5797
+ // src/internal/capture/aria-ref.ts
5798
+ function locatorOfRef(page, ref) {
5799
+ const getByRef = page.getByRef;
5800
+ return typeof getByRef === "function" ? getByRef.call(page, ref) : page.locator(`aria-ref=${ref}`);
5801
+ }
5802
+
5204
5803
  // src/internal/capture/pick-at.ts
5205
5804
  var LINE = /^(\s*)- ([a-z][\w-]*)(?: "(?:[^"\\]|\\.)*")?((?: \[[^\]\n]*\])*)(?::.*)?$/;
5206
5805
  var REF = /\[ref=(e\d+)\]/;
@@ -5240,18 +5839,16 @@ var PIWI_OVERLAY = '[id^="__piwi"], [id^="piwi-"][id$="-host"]';
5240
5839
  var MAX_UNDER = 24;
5241
5840
  var MAX_CHECKED = 8;
5242
5841
  var NORMALIZED_SCORE = 60;
5243
- var PICK_AT_NEEDS = "Pick on the image needs Playwright 1.64 or later (page.getByRef and the boxes of page.ariaSnapshot): update @playwright/test.";
5842
+ var PICK_AT_SINCE = "1.60";
5843
+ var PICK_AT_NEEDS = "Pick on the image needs Playwright 1.60 or later (the boxes of page.ariaSnapshot): update @playwright/test.";
5244
5844
  var NO_ELEMENT = "No element there: pick an element of the page, not its background.";
5245
5845
  var IN_IFRAME = "That point is in an iframe, whose elements Pick on the image does not reach: use Pick in the test's window.";
5246
- function canPickAt(page) {
5247
- return typeof page.getByRef === "function";
5248
- }
5249
5846
  var hitIn = ({ x, y, overlay, elements }) => {
5250
5847
  let scope = globalThis.document;
5251
5848
  let hit = null;
5252
5849
  for (let depth = 0; scope && depth < 32; depth++) {
5253
- const within3 = scope;
5254
- const top = within3.elementsFromPoint(x, y).find((el) => el.getRootNode?.() === within3 && !el.closest?.(overlay));
5850
+ const within4 = scope;
5851
+ const top = within4.elementsFromPoint(x, y).find((el) => el.getRootNode?.() === within4 && !el.closest?.(overlay));
5255
5852
  if (!top) break;
5256
5853
  hit = top;
5257
5854
  scope = top.shadowRoot ?? null;
@@ -5265,14 +5862,12 @@ var hitIn = ({ x, y, overlay, elements }) => {
5265
5862
  return -1;
5266
5863
  };
5267
5864
  async function pickAtPoint(page, probe, x, y) {
5268
- if (!canPickAt(page)) return { refusal: PICK_AT_NEEDS };
5269
5865
  const snapshot = await page.ariaSnapshot({ mode: "ai", boxes: true, timeout: 5e3 });
5270
5866
  if (!/\[box=/.test(snapshot)) return { refusal: PICK_AT_NEEDS };
5271
5867
  const under = boxesAt(snapshotBoxes(snapshot), x, y).slice(0, MAX_UNDER);
5272
- const byRef2 = (ref) => page.getByRef(ref);
5273
5868
  const handles = await Promise.all(
5274
5869
  under.map(
5275
- (box) => byRef2(box.ref).elementHandle({ timeout: 2e3 }).catch(() => null)
5870
+ (box) => locatorOfRef(page, box.ref).elementHandle({ timeout: 2e3 }).catch(() => null)
5276
5871
  )
5277
5872
  );
5278
5873
  try {
@@ -5289,7 +5884,7 @@ async function pickAtPoint(page, probe, x, y) {
5289
5884
  (el, overlay) => !!el.closest(overlay),
5290
5885
  PIWI_OVERLAY
5291
5886
  );
5292
- if (!piwi) return await rank(page, probe, byRef2(box.ref), handle);
5887
+ if (!piwi) return await rank(page, probe, locatorOfRef(page, box.ref), handle);
5293
5888
  }
5294
5889
  return { refusal: NO_ELEMENT };
5295
5890
  } finally {
@@ -5655,10 +6250,10 @@ var FrameAcks = class {
5655
6250
  const now = this.now();
5656
6251
  this.due = Math.min(Math.max(now, this.due + this.intervalMs), now + this.intervalMs);
5657
6252
  if (this.due <= now) return void 0;
5658
- return new Promise((resolve5) => {
6253
+ return new Promise((resolve6) => {
5659
6254
  const timer = setTimeout(() => this.release(), this.due - now);
5660
6255
  timer.unref?.();
5661
- this.waiting = { timer, resolve: resolve5 };
6256
+ this.waiting = { timer, resolve: resolve6 };
5662
6257
  });
5663
6258
  }
5664
6259
  /** Whether a frame waits for its acknowledgment. */
@@ -5682,6 +6277,7 @@ var FrameAcks = class {
5682
6277
  // ../core/src/run-channel.ts
5683
6278
  var RUN_CHANNEL_ENV = "PIWI_RUN_CHANNEL";
5684
6279
  var RUN_REF_ENV = "PIWI_RUN_REF";
6280
+ var TERMINAL_REF_PREFIX = "terminal-";
5685
6281
  var RUN_HOLDS = ["failure"];
5686
6282
  var RUN_INTENTS = ["pick", "record", "assert", "assert-region"];
5687
6283
  var RUN_TAKES = [
@@ -5839,48 +6435,377 @@ function parseHubToRun(line) {
5839
6435
  return typeof value.type === "string" && value.type ? unknown(value.type) : null;
5840
6436
  }
5841
6437
  }
5842
- function readAct(value) {
5843
- if (!isObject3(value) || !isSnapshotRef(value.ref)) return null;
5844
- const action = value.action;
5845
- if (typeof action !== "string" || !RUN_ACT_ACTIONS.includes(action)) return null;
5846
- const given = value.value;
5847
- switch (action) {
5848
- case "fill":
5849
- return typeof given === "string" && given.length <= MAX_ACT_VALUE ? { ref: value.ref, action: "fill", value: given } : null;
5850
- case "press":
5851
- return isViewKeyCombo(given) ? { ref: value.ref, action: "press", value: given } : null;
5852
- case "select":
5853
- return typeof given === "string" && given.length <= MAX_ACT_VALUE && !/[\r\n\0]/.test(given) ? { ref: value.ref, action: "select", value: given } : null;
5854
- default:
5855
- return given === null || given === void 0 ? { ref: value.ref, action, value: null } : null;
5856
- }
6438
+ function readAct(value) {
6439
+ if (!isObject3(value) || !isSnapshotRef(value.ref)) return null;
6440
+ const action = value.action;
6441
+ if (typeof action !== "string" || !RUN_ACT_ACTIONS.includes(action)) return null;
6442
+ const given = value.value;
6443
+ switch (action) {
6444
+ case "fill":
6445
+ return typeof given === "string" && given.length <= MAX_ACT_VALUE ? { ref: value.ref, action: "fill", value: given } : null;
6446
+ case "press":
6447
+ return isViewKeyCombo(given) ? { ref: value.ref, action: "press", value: given } : null;
6448
+ case "select":
6449
+ return typeof given === "string" && given.length <= MAX_ACT_VALUE && !/[\r\n\0]/.test(given) ? { ref: value.ref, action: "select", value: given } : null;
6450
+ default:
6451
+ return given === null || given === void 0 ? { ref: value.ref, action, value: null } : null;
6452
+ }
6453
+ }
6454
+
6455
+ // src/internal/capture/live-mask.ts
6456
+ var import_node_module2 = require("module");
6457
+ var MASKED_SPACING_MS = 500;
6458
+ var FRESH_MS = 1e3;
6459
+ var READS_KEPT = 4;
6460
+ var MAX_FRAMES = 32;
6461
+ var PAD = 2;
6462
+ var SAME_WITHIN = 1;
6463
+ var FRAME_READ_MS = 1e3;
6464
+ var MAX_FAILED_READS = 3;
6465
+ var MASK_RGB = [96, 96, 96];
6466
+ var TOO_MANY_FRAMES = `This page has more than ${MAX_FRAMES} frames: the live view cannot check them all for secret fields, so no image of it goes.`;
6467
+ var NO_CODEC = "A secret field shows on this page, and this Playwright gives the reporter nothing to mask it with: no image goes while it shows.";
6468
+ var UNREAD = "The live view cannot read where the secret fields of this page are, so no image of it goes until it can.";
6469
+ var ZOOMED = "This page is zoomed in: no image of it goes until it is not, its secret fields shown larger than read.";
6470
+ var UNREADABLE_MASKS = "The project masks elements this reporter cannot read: no image goes. Update @piwitests/reporter.";
6471
+ var codec;
6472
+ function jpegCodec() {
6473
+ if (codec !== void 0) return codec;
6474
+ codec = null;
6475
+ try {
6476
+ const playwright = resolvePlaywrightPackageJson();
6477
+ const bundle = playwright ? (0, import_node_module2.createRequire)(playwright)("playwright-core/lib/utilsBundle") : null;
6478
+ const found = bundle?.jpegjs;
6479
+ if (typeof found?.decode === "function" && typeof found.encode === "function") codec = found;
6480
+ } catch {
6481
+ }
6482
+ return codec;
6483
+ }
6484
+ function maskedIn(frame, masks) {
6485
+ let locator = frame.locator(SECRET_FIELD_SELECTOR);
6486
+ for (const source of masks) {
6487
+ const own = locatorOn(frame, source);
6488
+ if (!own) throw new Error(`The locator ${source} cannot be built.`);
6489
+ locator = locator.or(own);
6490
+ }
6491
+ return locator;
6492
+ }
6493
+ var unbuilt = (source) => `The project masks ${source}, which this Playwright cannot find elements by: no image of the page goes.`;
6494
+ var near = (a, b) => Math.abs(a - b) <= SAME_WITHIN;
6495
+ function readFrameRects(page, frame, masks) {
6496
+ return internalCall(
6497
+ page,
6498
+ () => maskedIn(frame, masks).evaluateAll((elements) => {
6499
+ const view3 = globalThis;
6500
+ const visual = view3.visualViewport;
6501
+ const layout = view3.document.scrollingElement;
6502
+ const zoomed = !!visual && (Math.abs(visual.offsetLeft) > 0.5 || Math.abs(visual.offsetTop) > 0.5 || (layout ? visual.width < layout.clientWidth - 1 || visual.height < layout.clientHeight - 1 : visual.scale > 1.001));
6503
+ return {
6504
+ rects: elements.map((element) => {
6505
+ const rect = element.getBoundingClientRect();
6506
+ return [rect.x, rect.y, rect.width, rect.height];
6507
+ }).filter(([, , width, height]) => width > 0 && height > 0),
6508
+ width: view3.innerWidth,
6509
+ height: view3.innerHeight,
6510
+ zoomed
6511
+ };
6512
+ })
6513
+ );
6514
+ }
6515
+ async function childOrigin(page, frame, inner) {
6516
+ return internalCall(page, async () => {
6517
+ const element = await frame.frameElement();
6518
+ try {
6519
+ const outer = await element.boundingBox();
6520
+ if (!outer) return null;
6521
+ const own = await element.evaluate((iframe) => {
6522
+ const el = iframe;
6523
+ const style = globalThis.getComputedStyle(iframe);
6524
+ const pad = (side) => parseFloat(side) || 0;
6525
+ return {
6526
+ left: el.clientLeft + pad(style.paddingLeft),
6527
+ top: el.clientTop + pad(style.paddingTop),
6528
+ width: el.clientWidth - pad(style.paddingLeft) - pad(style.paddingRight),
6529
+ height: el.clientHeight - pad(style.paddingTop) - pad(style.paddingBottom),
6530
+ offsetWidth: el.offsetWidth,
6531
+ offsetHeight: el.offsetHeight
6532
+ };
6533
+ });
6534
+ const drawnAsLaidOut = near(outer.width, own.offsetWidth) && near(outer.height, own.offsetHeight);
6535
+ const contentIsViewport = near(own.width, inner.width) && near(own.height, inner.height);
6536
+ if (!drawnAsLaidOut || !contentIsViewport) return { whole: outer };
6537
+ return { x: outer.x + own.left, y: outer.y + own.top };
6538
+ } finally {
6539
+ await element.dispose();
6540
+ }
6541
+ });
6542
+ }
6543
+ async function within2(run, ms) {
6544
+ let timer;
6545
+ try {
6546
+ return await Promise.race([
6547
+ run,
6548
+ new Promise((resolve6) => timer = setTimeout(() => resolve6(void 0), ms))
6549
+ ]);
6550
+ } finally {
6551
+ clearTimeout(timer);
6552
+ }
6553
+ }
6554
+ async function wholeFrame(page, frame) {
6555
+ const box = await within2(
6556
+ internalCall(page, async () => {
6557
+ const element = await frame.frameElement();
6558
+ try {
6559
+ return await element.boundingBox();
6560
+ } finally {
6561
+ await element.dispose();
6562
+ }
6563
+ }),
6564
+ FRAME_READ_MS
6565
+ ).catch(() => void 0);
6566
+ if (box === void 0) return null;
6567
+ return { rects: box ? [[box.x, box.y, box.width, box.height]] : [], width: 0, height: 0 };
6568
+ }
6569
+ async function readFrame(page, frame, masks) {
6570
+ try {
6571
+ const read = await within2(readFrameRects(page, frame, masks), FRAME_READ_MS);
6572
+ if (!read) return frame === page.mainFrame() ? null : await wholeFrame(page, frame);
6573
+ if (!read.rects.length || frame === page.mainFrame()) return read;
6574
+ const origin = await childOrigin(page, frame, read);
6575
+ if (!origin) return { ...read, rects: [] };
6576
+ if ("whole" in origin) {
6577
+ const { x, y, width, height } = origin.whole;
6578
+ return { ...read, rects: [[x, y, width, height]] };
6579
+ }
6580
+ return {
6581
+ ...read,
6582
+ rects: read.rects.map(([left, top, width, height]) => [origin.x + left, origin.y + top, width, height])
6583
+ };
6584
+ } catch {
6585
+ return frame.isDetached() ? { rects: [], width: 0, height: 0 } : null;
6586
+ }
6587
+ }
6588
+ async function readBoxes(page, masks) {
6589
+ if (!masks) return UNREADABLE_MASKS;
6590
+ const frames = page.frames();
6591
+ if (frames.length > MAX_FRAMES) return TOO_MANY_FRAMES;
6592
+ for (const source of masks) if (!locatorOn(page.mainFrame(), source)) return unbuilt(source);
6593
+ const main = page.mainFrame();
6594
+ const read = await Promise.all(frames.map((frame) => readFrame(page, frame, masks)));
6595
+ if (read.some((frame) => frame === null)) return null;
6596
+ const top = read[frames.indexOf(main)];
6597
+ if (!top) return null;
6598
+ if (top.zoomed) return ZOOMED;
6599
+ return {
6600
+ boxes: read.flatMap(
6601
+ (frame) => frame.rects.map(([x, y, width, height]) => ({ x, y, width, height }))
6602
+ ),
6603
+ viewport: { width: top.width, height: top.height }
6604
+ };
6605
+ }
6606
+ function sameBoxes(a, b) {
6607
+ return a.length === b.length && a.every((box, i) => {
6608
+ const other = b[i];
6609
+ return Math.abs(box.x - other.x) <= SAME_WITHIN && Math.abs(box.y - other.y) <= SAME_WITHIN && Math.abs(box.width - other.width) <= SAME_WITHIN && Math.abs(box.height - other.height) <= SAME_WITHIN;
6610
+ });
6611
+ }
6612
+ function jpegSize(data) {
6613
+ for (let i = 2; i + 9 < data.length; ) {
6614
+ if (data[i] !== 255) return null;
6615
+ const marker = data[i + 1];
6616
+ if (marker >= 192 && marker <= 195) return { height: data.readUInt16BE(i + 5), width: data.readUInt16BE(i + 7) };
6617
+ i += 2 + data.readUInt16BE(i + 2);
6618
+ }
6619
+ return null;
6620
+ }
6621
+ function shrink(image, width, height) {
6622
+ const data = new Uint8Array(width * height * 4);
6623
+ const sx = image.width / width;
6624
+ const sy = image.height / height;
6625
+ for (let y = 0; y < height; y++) {
6626
+ const y0 = Math.floor(y * sy);
6627
+ const y1 = Math.max(y0 + 1, Math.min(image.height, Math.floor((y + 1) * sy)));
6628
+ for (let x = 0; x < width; x++) {
6629
+ const x0 = Math.floor(x * sx);
6630
+ const x1 = Math.max(x0 + 1, Math.min(image.width, Math.floor((x + 1) * sx)));
6631
+ let r = 0;
6632
+ let g = 0;
6633
+ let b = 0;
6634
+ for (let yy = y0; yy < y1; yy++) {
6635
+ for (let xx = x0; xx < x1; xx++) {
6636
+ const i = (yy * image.width + xx) * 4;
6637
+ r += image.data[i];
6638
+ g += image.data[i + 1];
6639
+ b += image.data[i + 2];
6640
+ }
6641
+ }
6642
+ const n = (y1 - y0) * (x1 - x0);
6643
+ const o = (y * width + x) * 4;
6644
+ data[o] = r / n;
6645
+ data[o + 1] = g / n;
6646
+ data[o + 2] = b / n;
6647
+ data[o + 3] = 255;
6648
+ }
6649
+ }
6650
+ return { width, height, data };
6651
+ }
6652
+ function paintBoxes(jpeg, frame, boxes, size, quality) {
6653
+ const image = jpeg.decode(frame.data, { useTArray: true, formatAsRGBA: true });
6654
+ const sx = image.width / frame.width;
6655
+ const sy = image.height / frame.height;
6656
+ for (const box of boxes) {
6657
+ const x0 = Math.max(0, Math.floor((box.x - PAD) * sx));
6658
+ const y0 = Math.max(0, Math.floor((box.y - PAD) * sy));
6659
+ const x1 = Math.min(image.width, Math.ceil((box.x + box.width + PAD) * sx));
6660
+ const y1 = Math.min(image.height, Math.ceil((box.y + box.height + PAD) * sy));
6661
+ for (let y = y0; y < y1; y++) {
6662
+ for (let x = x0; x < x1; x++) {
6663
+ const i = (y * image.width + x) * 4;
6664
+ image.data[i] = MASK_RGB[0];
6665
+ image.data[i + 1] = MASK_RGB[1];
6666
+ image.data[i + 2] = MASK_RGB[2];
6667
+ image.data[i + 3] = 255;
6668
+ }
6669
+ }
6670
+ }
6671
+ const fits = image.width <= size.width && image.height <= size.height;
6672
+ return jpeg.encode(fits ? image : shrink(image, size.width, size.height), quality).data;
6673
+ }
6674
+ async function measureFrame(page, frame) {
6675
+ try {
6676
+ const measured = await within2(
6677
+ internalCall(page, async () => {
6678
+ const fields = await frame.locator(SECRET_FIELD_SELECTOR).elementHandles();
6679
+ try {
6680
+ return await Promise.all(fields.map((field) => field.boundingBox()));
6681
+ } finally {
6682
+ await Promise.all(fields.map((field) => field.dispose().catch(() => void 0)));
6683
+ }
6684
+ }),
6685
+ FRAME_READ_MS
6686
+ );
6687
+ if (measured) return measured.filter((box) => !!box && box.width > 0 && box.height > 0);
6688
+ const whole = frame === page.mainFrame() ? null : await wholeFrame(page, frame);
6689
+ return whole && whole.rects.map(([x, y, width, height]) => ({ x, y, width, height }));
6690
+ } catch {
6691
+ return frame.isDetached() ? [] : null;
6692
+ }
6693
+ }
6694
+ async function secretBoxes(page) {
6695
+ const [read, measured] = await Promise.all([
6696
+ readBoxes(page, []),
6697
+ Promise.all(
6698
+ page.frames().slice(0, MAX_FRAMES).map((frame) => measureFrame(page, frame))
6699
+ )
6700
+ ]);
6701
+ if (!read || typeof read === "string" || measured.some((boxes) => !boxes)) return null;
6702
+ return { ...read, boxes: [...read.boxes, ...measured.flat()] };
6703
+ }
6704
+ async function maskedImage(page, options) {
6705
+ const before = await secretBoxes(page);
6706
+ if (!before) return null;
6707
+ const shot = await internalCall(
6708
+ page,
6709
+ () => page.screenshot({
6710
+ type: "jpeg",
6711
+ quality: options.quality,
6712
+ timeout: options.timeout,
6713
+ ...options.style ? { style: options.style } : {}
6714
+ })
6715
+ ).catch(() => null);
6716
+ if (!shot) return null;
6717
+ const after = await secretBoxes(page);
6718
+ if (!after || !sameBoxes(before.boxes, after.boxes)) return null;
6719
+ const { width, height } = after.viewport;
6720
+ if (!near(width, before.viewport.width) || !near(height, before.viewport.height)) return null;
6721
+ if (!after.boxes.length) return shot;
6722
+ const jpeg = jpegCodec();
6723
+ const size = jpegSize(shot);
6724
+ if (!jpeg || !size) return null;
6725
+ try {
6726
+ return paintBoxes(jpeg, { data: shot, width, height, at: Date.now() }, after.boxes, size, options.quality);
6727
+ } catch {
6728
+ return null;
6729
+ }
6730
+ }
6731
+ function maskSecretFields(page, options) {
6732
+ const reads = [];
6733
+ let maskedAt = -Infinity;
6734
+ let failed2 = 0;
6735
+ const read = async () => {
6736
+ const began = Date.now();
6737
+ const found = await readBoxes(page, options.masks());
6738
+ if (typeof found === "string") return found;
6739
+ if (!found) return ++failed2 >= MAX_FAILED_READS ? UNREAD : null;
6740
+ failed2 = 0;
6741
+ const done = { began, ended: Date.now(), ...found };
6742
+ reads.push(done);
6743
+ if (reads.length > READS_KEPT) reads.shift();
6744
+ return done;
6745
+ };
6746
+ const showsViewportOf = (frame, read2) => near(frame.width, read2.viewport.width) && near(frame.height, read2.viewport.height);
6747
+ const shown2 = (frame, boxes, size) => {
6748
+ const own = jpegSize(frame.data);
6749
+ const fits = own === null || own.width <= size.width && own.height <= size.height;
6750
+ const jpeg = jpegCodec();
6751
+ if (!boxes.length && (fits || !jpeg)) return frame.data.length <= options.maxBytes ? frame : null;
6752
+ if (!jpeg) return NO_CODEC;
6753
+ let data;
6754
+ try {
6755
+ data = paintBoxes(jpeg, frame, boxes, size, options.quality);
6756
+ } catch {
6757
+ return null;
6758
+ }
6759
+ if (!boxes.length) return data.length <= options.maxBytes ? { ...frame, data } : null;
6760
+ if (data.length > options.maxBytes) return null;
6761
+ maskedAt = Date.now();
6762
+ return { ...frame, data };
6763
+ };
6764
+ return {
6765
+ get resting() {
6766
+ return Date.now() - maskedAt < MASKED_SPACING_MS;
6767
+ },
6768
+ async screen(frame) {
6769
+ const before = [...reads].reverse().find((r) => r.ended <= frame.at && r.ended >= frame.at - FRESH_MS) ?? null;
6770
+ const after = await read();
6771
+ if (typeof after === "string" || !after) return after;
6772
+ const size = jpegSize(frame.data) ?? frame;
6773
+ if (before && sameBoxes(before.boxes, after.boxes) && showsViewportOf(frame, before) && showsViewportOf(frame, after)) {
6774
+ return shown2(frame, after.boxes, size);
6775
+ }
6776
+ if (page.isClosed()) return null;
6777
+ const at = Date.now();
6778
+ const shot = await internalCall(
6779
+ page,
6780
+ () => page.screenshot({ type: "jpeg", quality: options.quality, scale: "css", caret: "initial", timeout: 5e3 })
6781
+ ).catch(() => null);
6782
+ if (!shot) return null;
6783
+ const again = await read();
6784
+ if (typeof again === "string" || !again) return again;
6785
+ if (!sameBoxes(after.boxes, again.boxes)) return null;
6786
+ const { width, height } = again.viewport;
6787
+ if (!near(width, after.viewport.width) || !near(height, after.viewport.height)) return null;
6788
+ return shown2(
6789
+ { data: shot, width, height, at },
6790
+ again.boxes,
6791
+ fitViewSize({ width, height }, size.width, size.height)
6792
+ );
6793
+ }
6794
+ };
5857
6795
  }
5858
6796
 
5859
6797
  // src/internal/capture/agent-page.ts
5860
6798
  var ACT_MS = 5e3;
5861
- var SECRET_FIELDS = [
5862
- 'input[type="password" i]',
5863
- ...SECRET_AUTOCOMPLETE.flatMap((token) => [
5864
- `input[autocomplete~="${token}" i]`,
5865
- `textarea[autocomplete~="${token}" i]`
5866
- ])
5867
- ].join(", ");
6799
+ var SECRET_FIELDS = SECRET_FIELD_SELECTOR;
5868
6800
  var BAR_HIDDEN = "#__piwi-pause-bar { display: none !important; }";
5869
- var AGENT_NEEDS = "An agent reads and acts on a stopped page with Playwright 1.64 or later (page.getByRef and the AI snapshot): update @playwright/test.";
5870
- function canActByRef(page) {
5871
- return typeof page.getByRef === "function";
5872
- }
5873
- function byRef(page, ref) {
5874
- return page.getByRef(ref);
5875
- }
5876
6801
  function failed(prefix, error) {
5877
6802
  const first = errorMessage(error).split("\n")[0].trim();
5878
6803
  return hideSecretsInText(`${prefix}: ${first}`).slice(0, 300);
5879
6804
  }
5880
- var MAX_FRAMES = 32;
6805
+ var MAX_FRAMES2 = 32;
5881
6806
  async function fieldSecrets(page) {
5882
6807
  const values = await Promise.all(
5883
- page.frames().slice(0, MAX_FRAMES).map(
6808
+ page.frames().slice(0, MAX_FRAMES2).map(
5884
6809
  (frame) => frame.locator(SECRET_FIELDS).evaluateAll((fields) => fields.map((field) => field.value)).catch(() => [])
5885
6810
  )
5886
6811
  );
@@ -5934,13 +6859,7 @@ async function readSnapshot(page, depth, image) {
5934
6859
  const cut = hidden2.length > MAX_AGENT_SNAPSHOT;
5935
6860
  let shot = null;
5936
6861
  if (image) {
5937
- const data = await page.screenshot({
5938
- type: "jpeg",
5939
- quality: 60,
5940
- style: BAR_HIDDEN,
5941
- mask: page.frames().slice(0, MAX_FRAMES).map((frame) => frame.locator(SECRET_FIELDS)),
5942
- timeout: ACT_MS
5943
- }).catch(() => null);
6862
+ const data = await maskedImage(page, { quality: 60, style: BAR_HIDDEN, timeout: ACT_MS });
5944
6863
  const viewport = page.viewportSize();
5945
6864
  if (data) shot = { mime: "image/jpeg", data: data.toString("base64"), ...viewport };
5946
6865
  }
@@ -6009,14 +6928,13 @@ async function ranked(page, probe, locator, handle, testIdAttribute) {
6009
6928
  }
6010
6929
  var NO_REF = (ref) => `No element of the stopped page has the ref ${ref}: take the page's snapshot again, its refs may have changed.`;
6011
6930
  async function handleOf(page, ref) {
6012
- return byRef(page, ref).elementHandle({ timeout: 2e3 }).catch(() => null);
6931
+ return locatorOfRef(page, ref).elementHandle({ timeout: 2e3 }).catch(() => null);
6013
6932
  }
6014
6933
  async function refLocators(page, probe, ref, testIdAttribute) {
6015
- if (!canActByRef(page)) return { ok: false, message: AGENT_NEEDS, element: null, locators: [] };
6016
6934
  const handle = await handleOf(page, ref);
6017
6935
  if (!handle) return { ok: false, message: NO_REF(ref), element: null, locators: [] };
6018
6936
  try {
6019
- const { element, locators } = await ranked(page, probe, byRef(page, ref), handle, testIdAttribute);
6937
+ const { element, locators } = await ranked(page, probe, locatorOfRef(page, ref), handle, testIdAttribute);
6020
6938
  const alone = locators.filter((l) => l.unique).length;
6021
6939
  return {
6022
6940
  ok: true,
@@ -6060,12 +6978,11 @@ var PLAYED = {
6060
6978
  select: "Selected an option of"
6061
6979
  };
6062
6980
  async function actOnRef(page, probe, act, testIdAttribute) {
6063
- if (!canActByRef(page)) return { ok: false, message: AGENT_NEEDS, element: null, locators: [] };
6064
6981
  const handle = await handleOf(page, act.ref);
6065
6982
  if (!handle) return { ok: false, message: NO_REF(act.ref), element: null, locators: [] };
6066
6983
  let before;
6067
6984
  try {
6068
- before = await ranked(page, probe, byRef(page, act.ref), handle, testIdAttribute);
6985
+ before = await ranked(page, probe, locatorOfRef(page, act.ref), handle, testIdAttribute);
6069
6986
  } catch (error) {
6070
6987
  return { ok: false, message: failed("The element could not be read", error), element: null, locators: [] };
6071
6988
  } finally {
@@ -6073,7 +6990,7 @@ async function actOnRef(page, probe, act, testIdAttribute) {
6073
6990
  }
6074
6991
  try {
6075
6992
  await page.evaluate(barLetsThrough, true).catch(() => void 0);
6076
- await play(byRef(page, act.ref), act.action, act.value);
6993
+ await play(locatorOfRef(page, act.ref), act.action, act.value);
6077
6994
  } catch (error) {
6078
6995
  return { ok: false, message: failed(`${PLAYED[act.action]} ${act.ref} failed`, error), ...before };
6079
6996
  } finally {
@@ -6117,7 +7034,7 @@ async function bindBrowser(browser, name, workspaceDir, on) {
6117
7034
  }
6118
7035
 
6119
7036
  // src/internal/capture/run-events.ts
6120
- var path9 = __toESM(require("path"));
7037
+ var path11 = __toESM(require("path"));
6121
7038
 
6122
7039
  // src/internal/capture/run-channel.ts
6123
7040
  var net = __toESM(require("net"));
@@ -6132,8 +7049,8 @@ function parseRecordChannel(value) {
6132
7049
  const hash = text.lastIndexOf("#");
6133
7050
  if (hash <= 0) return null;
6134
7051
  const token = text.slice(hash + 1);
6135
- const path16 = text.slice(0, hash);
6136
- return /^[A-Za-z0-9_-]{16,}$/.test(token) && !path16.includes("\0") ? { path: path16, token } : null;
7052
+ const path19 = text.slice(0, hash);
7053
+ return /^[A-Za-z0-9_-]{16,}$/.test(token) && !path19.includes("\0") ? { path: path19, token } : null;
6137
7054
  }
6138
7055
  function isObject4(value) {
6139
7056
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -6177,6 +7094,16 @@ function lineReader(onLine, onOverflow) {
6177
7094
  };
6178
7095
  }
6179
7096
 
7097
+ // src/internal/config/editors.ts
7098
+ var fs7 = __toESM(require("fs"));
7099
+ var os2 = __toESM(require("os"));
7100
+ var path9 = __toESM(require("path"));
7101
+ var TEST_RUNNER_REPORTER_ENV = "PW_TEST_REPORTER";
7102
+ function startedByTestRunner(env) {
7103
+ const reporter = env[TEST_RUNNER_REPORTER_ENV]?.trim();
7104
+ return !!reporter && /[\\/]/.test(reporter);
7105
+ }
7106
+
6180
7107
  // src/internal/capture/kept-responses.ts
6181
7108
  var keeping = null;
6182
7109
  var TEXT_TYPE = /^(?:text\/[\w.+-]+|application\/(?:[\w.+-]+\+)?(?:json|xml)|application\/(?:javascript|x-www-form-urlencoded|graphql))$/i;
@@ -6261,6 +7188,8 @@ var LIVE_FRAME_BYTE_RATE = 256 * 1024;
6261
7188
  var MAX_LIVE_FRAME = 192 * 1024;
6262
7189
  var MAX_LIVE_FRAME_BASE64 = 4 * Math.ceil(MAX_LIVE_FRAME / 3);
6263
7190
  var MAX_LIVE_MESSAGE = MAX_LIVE_FRAME_BASE64 + 8 * 1024;
7191
+ var MAX_LIVE_CALL_LOG_LINES = 20;
7192
+ var LIVE_CALL_LOGS_PER_SECOND = 4;
6264
7193
  var KEY = /^pdl_[A-Za-z0-9_-]{43}$/;
6265
7194
  function isLiveViewKey(value) {
6266
7195
  return typeof value === "string" && KEY.test(value);
@@ -6318,12 +7247,68 @@ function liveShareRefusal(status) {
6318
7247
  return "Sharing stopped: the instance did not answer. Share the run again to try once more.";
6319
7248
  }
6320
7249
  }
7250
+ var MAX_LIVE_MASKS = 20;
7251
+ var MAX_LIVE_MASK_LENGTH = 200;
7252
+ var FRAME_CALLS = /* @__PURE__ */ new Set(["frameLocator", "contentFrame", "owner"]);
7253
+ var NARROWING_CALLS = /* @__PURE__ */ new Set(["filter", "and", "or", "visible", "first", "last", "nth"]);
7254
+ function liveMaskProblem(locator) {
7255
+ if (!locator.trim()) return "A masked element needs a locator.";
7256
+ if (locator.length > MAX_LIVE_MASK_LENGTH) return `A locator is ${MAX_LIVE_MASK_LENGTH} characters at most.`;
7257
+ const source = locator.trim();
7258
+ const chain = tryParseLocatorChain(source);
7259
+ if (!chain?.calls.length || NARROWING_CALLS.has(chain.calls[0].method)) {
7260
+ return `\`${source}\` is not a Playwright locator, such as getByLabel('IBAN').`;
7261
+ }
7262
+ if (chain.calls.some((call) => FRAME_CALLS.has(call.method))) {
7263
+ return `\`${source}\` enters a frame: masks are looked for in every frame of the page, so name the element alone, such as getByLabel('Card number'), or the iframe, such as locator('iframe#card').`;
7264
+ }
7265
+ return null;
7266
+ }
7267
+ function parseLiveMasks(value) {
7268
+ if (!Array.isArray(value) || value.length > MAX_LIVE_MASKS) return null;
7269
+ const locators = [];
7270
+ for (const locator of value) {
7271
+ if (typeof locator !== "string" || liveMaskProblem(locator)) return null;
7272
+ if (!locators.includes(locator.trim())) locators.push(locator.trim());
7273
+ }
7274
+ return locators;
7275
+ }
6321
7276
  function isObject5(value) {
6322
7277
  return typeof value === "object" && value !== null && !Array.isArray(value);
6323
7278
  }
6324
7279
  function isInt2(value, min, max) {
6325
7280
  return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
6326
7281
  }
7282
+ var LONGEST_REPEAT = 12;
7283
+ function sameLines(lines, a, b, size) {
7284
+ for (let k = 0; k < size; k++) if (lines[a + k] !== lines[b + k]) return false;
7285
+ return true;
7286
+ }
7287
+ function compressCallLog(lines) {
7288
+ const out = [];
7289
+ let i = 0;
7290
+ while (i < lines.length) {
7291
+ let size = 1;
7292
+ let count = 1;
7293
+ for (let length = 1; length <= LONGEST_REPEAT && i + length * 2 <= lines.length; length++) {
7294
+ let times = 1;
7295
+ while (i + length * (times + 1) <= lines.length && sameLines(lines, i, i + length * times, length)) times++;
7296
+ if (times > 1 && times * length > count * size) {
7297
+ size = length;
7298
+ count = times;
7299
+ }
7300
+ }
7301
+ for (let k = 0; k < size; k++) {
7302
+ const line = lines[i + k];
7303
+ const indent = /^\s*/.exec(line)[0];
7304
+ if (count === 1) out.push(`${indent}- ${line.trim()}`);
7305
+ else if (k === 0) out.push(`${indent}${count} \xD7 ${line.trim()}`);
7306
+ else out.push(`${indent}${" ".repeat(`${count} \xD7 `.length - 2)}- ${line.trim()}`);
7307
+ }
7308
+ i += size * count;
7309
+ }
7310
+ return out;
7311
+ }
6327
7312
  function parseInstanceToWorker(data) {
6328
7313
  let value;
6329
7314
  try {
@@ -6331,7 +7316,9 @@ function parseInstanceToWorker(data) {
6331
7316
  } catch {
6332
7317
  return null;
6333
7318
  }
6334
- if (!isObject5(value) || value.type !== "viewers" || !isInt2(value.count, 0, 1e6)) return null;
7319
+ if (!isObject5(value)) return null;
7320
+ if (value.type === "masks") return { type: "masks", locators: parseLiveMasks(value.locators) };
7321
+ if (value.type !== "viewers" || !isInt2(value.count, 0, 1e6)) return null;
6335
7322
  return { type: "viewers", count: value.count };
6336
7323
  }
6337
7324
 
@@ -6349,7 +7336,198 @@ function resolveShardInfo(config, env = process.env) {
6349
7336
  return parseShardSpec(env[PIWI_SHARD_ENV]);
6350
7337
  }
6351
7338
 
7339
+ // src/internal/capture/live-call-log.ts
7340
+ var path10 = __toESM(require("path"));
7341
+ var TARGET_EVERY_MS = 1e3;
7342
+ var KEPT_LINES = 1e3;
7343
+ var MAX_LINE2 = 600;
7344
+ var MAX_TITLE = 500;
7345
+ var MAX_HEARD = 200;
7346
+ function callStreamOf(context) {
7347
+ const dbg = context.debugger;
7348
+ return typeof dbg?._enable === "function" && typeof dbg.on === "function" && typeof dbg.off === "function" ? dbg : null;
7349
+ }
7350
+ var heard = /* @__PURE__ */ new Map();
7351
+ var tracked = /* @__PURE__ */ new WeakSet();
7352
+ function trackCalls(playwright) {
7353
+ const instrumentation = playwright?._instrumentation;
7354
+ if (!playwright || tracked.has(playwright) || typeof instrumentation?.addListener !== "function") return;
7355
+ tracked.add(playwright);
7356
+ instrumentation.addListener({
7357
+ onApiCallBegin: (zone, channel) => {
7358
+ if (channel?.method === "__waitInfo__") return;
7359
+ const selector = channel?.params?.selector;
7360
+ heard.set(zone, {
7361
+ zone,
7362
+ selector: typeof selector === "string" && selector ? selector : null,
7363
+ began: Date.now()
7364
+ });
7365
+ if (heard.size > MAX_HEARD) heard.delete(heard.keys().next().value);
7366
+ },
7367
+ onApiCallEnd: (zone) => {
7368
+ heard.delete(zone);
7369
+ }
7370
+ });
7371
+ }
7372
+ function heardAs(id) {
7373
+ for (const call of heard.values()) if (call.zone.callId === id) return call;
7374
+ return null;
7375
+ }
7376
+ function userFile(file) {
7377
+ if (typeof file !== "string" || !file || /[\\/]node_modules[\\/]/.test(file)) return null;
7378
+ const relative7 = path10.relative(process.cwd(), file).split(path10.sep).join("/");
7379
+ return relative7 && !relative7.startsWith("..") && !path10.isAbsolute(relative7) ? relative7 : null;
7380
+ }
7381
+ var followed = /* @__PURE__ */ new WeakMap();
7382
+ function take(state, update) {
7383
+ if (typeof update?.id !== "string" || typeof update.title !== "string") return;
7384
+ const status = update.status === "running" ? "running" : update.status === "error" ? "failed" : "passed";
7385
+ let call = state.calls.get(update.id);
7386
+ if (!call) {
7387
+ const heardOne = heardAs(update.id);
7388
+ call = {
7389
+ id: update.id,
7390
+ title: hideSecretsInText(hideTypedText(update.title)).slice(0, MAX_TITLE),
7391
+ file: userFile(update.location?.file),
7392
+ line: typeof update.location?.line === "number" ? update.location.line : null,
7393
+ status,
7394
+ lines: [],
7395
+ point: null,
7396
+ error: null,
7397
+ began: heardOne?.began ?? Date.now(),
7398
+ ended: null,
7399
+ order: ++state.told,
7400
+ selector: heardOne?.selector ?? null,
7401
+ secretField: heardOne?.selector ? isSecretLocator(heardOne.selector) : false
7402
+ };
7403
+ state.calls.set(update.id, call);
7404
+ }
7405
+ if (Array.isArray(update.newLogEntries)) {
7406
+ for (const entry of update.newLogEntries) {
7407
+ if (typeof entry !== "string") continue;
7408
+ call.secretField ||= namesSecretField(entry);
7409
+ call.lines.push(hideSecretsInText(hideSecretsInLog(entry, call.secretField)).slice(0, MAX_LINE2));
7410
+ }
7411
+ if (call.lines.length > KEPT_LINES) call.lines.splice(0, call.lines.length - KEPT_LINES);
7412
+ }
7413
+ const point = update.actionPoint;
7414
+ if (point && Number.isFinite(point.x) && Number.isFinite(point.y)) {
7415
+ call.point = { x: point.x, y: point.y };
7416
+ }
7417
+ if (typeof update.error === "string" && update.error) {
7418
+ const first = update.error.split("\n")[0];
7419
+ call.error = hideSecretsInText(hideSecretsInLog(first, call.secretField)).slice(0, MAX_LINE2);
7420
+ }
7421
+ call.status = status;
7422
+ if (status !== "running" && call.ended === null) call.ended = Date.now();
7423
+ }
7424
+ function shownCall(state, since) {
7425
+ let shown2 = null;
7426
+ for (const call of state.calls.values()) {
7427
+ if (call.ended !== null && call.ended < since) continue;
7428
+ if (!shown2) {
7429
+ shown2 = call;
7430
+ continue;
7431
+ }
7432
+ const running2 = call.status === "running";
7433
+ if (running2 !== (shown2.status === "running") ? running2 : call.order > shown2.order) shown2 = call;
7434
+ }
7435
+ return shown2;
7436
+ }
7437
+ function prune(state) {
7438
+ let last = null;
7439
+ for (const call of state.calls.values()) if (!last || call.order > last.order) last = call;
7440
+ for (const [id, call] of state.calls) if (call.status !== "running" && call !== last) state.calls.delete(id);
7441
+ }
7442
+ async function followContext(context) {
7443
+ const stream = callStreamOf(context);
7444
+ if (!stream) return null;
7445
+ const state = { calls: /* @__PURE__ */ new Map(), told: 0, views: /* @__PURE__ */ new Set() };
7446
+ const listener = (updates) => {
7447
+ if (!Array.isArray(updates)) return;
7448
+ for (const update of updates) take(state, update);
7449
+ prune(state);
7450
+ for (const view3 of state.views) view3();
7451
+ };
7452
+ stream.on("apicallsupdated", listener);
7453
+ try {
7454
+ await internalCall(context, () => stream._enable());
7455
+ } catch {
7456
+ stream.off("apicallsupdated", listener);
7457
+ return null;
7458
+ }
7459
+ return state;
7460
+ }
7461
+ async function followCallLog(page, since, onLog) {
7462
+ const context = page.context();
7463
+ let state = followed.get(context);
7464
+ if (!state) {
7465
+ state = followContext(context);
7466
+ followed.set(context, state);
7467
+ }
7468
+ const calls = await state;
7469
+ if (!calls) return null;
7470
+ let stopped = false;
7471
+ let reading = false;
7472
+ let target = null;
7473
+ const onThisPage = () => !page.isClosed() && context.pages().length === 1;
7474
+ const tell = () => {
7475
+ const shown2 = shownCall(calls, since);
7476
+ if (stopped || !shown2) return;
7477
+ const here = onThisPage();
7478
+ onLog({
7479
+ id: shown2.id,
7480
+ call: { title: shown2.title, file: shown2.file, line: shown2.line },
7481
+ status: shown2.status,
7482
+ lines: compressCallLog(shown2.lines).slice(-MAX_LIVE_CALL_LOG_LINES),
7483
+ point: here ? shown2.point : null,
7484
+ target: here && shown2.status === "running" && target?.id === shown2.id ? target.matches : null,
7485
+ viewport: page.viewportSize(),
7486
+ ms: (shown2.ended ?? Date.now()) - shown2.began,
7487
+ error: shown2.error
7488
+ });
7489
+ };
7490
+ calls.views.add(tell);
7491
+ tell();
7492
+ const timer = setInterval(() => {
7493
+ const shown2 = shownCall(calls, since);
7494
+ const selector = shown2?.selector;
7495
+ if (stopped || reading || !shown2 || shown2.status !== "running" || !selector || !onThisPage()) return;
7496
+ if (Date.now() - shown2.began < TARGET_EVERY_MS) return;
7497
+ reading = true;
7498
+ const framed = selector.includes("internal:control=enter-frame");
7499
+ void internalCall(
7500
+ page,
7501
+ () => page.locator(selector).evaluateAll((elements) => {
7502
+ const first = elements[0];
7503
+ if (!first) return { count: 0, box: null, enabled: null };
7504
+ const rect = first.getBoundingClientRect();
7505
+ const disabled = first.disabled === true || first.getAttribute("aria-disabled") === "true";
7506
+ return {
7507
+ count: elements.length,
7508
+ box: rect.width || rect.height ? { x: rect.x, y: rect.y, width: rect.width, height: rect.height } : null,
7509
+ enabled: !disabled
7510
+ };
7511
+ })
7512
+ ).then((matches) => {
7513
+ if (stopped || shownCall(calls, since) !== shown2 || shown2.status !== "running") return;
7514
+ if (!matches.count && shown2.lines.some((line) => line.includes("locator resolved to"))) return;
7515
+ target = { id: shown2.id, matches: framed ? { ...matches, box: null } : matches };
7516
+ tell();
7517
+ }).catch(() => void 0).finally(() => {
7518
+ reading = false;
7519
+ });
7520
+ }, TARGET_EVERY_MS);
7521
+ timer.unref?.();
7522
+ return () => {
7523
+ stopped = true;
7524
+ clearInterval(timer);
7525
+ calls.views.delete(tell);
7526
+ };
7527
+ }
7528
+
6352
7529
  // src/internal/capture/page-view.ts
7530
+ var SCREENCAST_LAG_MS = 100;
6353
7531
  var HOLDERS = /* @__PURE__ */ new WeakMap();
6354
7532
  var TEST_SCREENCASTS = /* @__PURE__ */ new WeakSet();
6355
7533
  var OWN_SCREENCASTS = /* @__PURE__ */ new WeakMap();
@@ -6402,16 +7580,39 @@ async function openPageView(page, options) {
6402
7580
  let last = null;
6403
7581
  let sent2 = null;
6404
7582
  let refused = false;
7583
+ let screening = false;
7584
+ let screened = null;
6405
7585
  const interval = 1e3 / options.fps;
7586
+ const deliver = (frame) => {
7587
+ if (closed || !options.live()) return;
7588
+ refused = false;
7589
+ sent2 = frame;
7590
+ options.send(frame);
7591
+ };
7592
+ const refuse2 = (why) => {
7593
+ if (closed || refused || !options.live()) return;
7594
+ refused = true;
7595
+ sent2 = { refused: why };
7596
+ options.refuse(why);
7597
+ };
6406
7598
  const pacer = new LatestPacer({
6407
7599
  intervalMs: interval,
6408
7600
  ...options.spacing ? { spacing: options.spacing } : {},
6409
- busy: options.busy,
7601
+ busy: () => screening || options.busy(),
6410
7602
  send: (frame) => {
6411
7603
  if (!options.live()) return;
6412
- refused = false;
6413
- sent2 = frame;
6414
- options.send(frame);
7604
+ if (!options.screen) return deliver(frame);
7605
+ screening = true;
7606
+ screened = options.screen(frame).then(
7607
+ (shown2) => {
7608
+ if (typeof shown2 === "string") refuse2(shown2);
7609
+ else if (shown2) deliver(shown2);
7610
+ },
7611
+ () => void 0
7612
+ ).finally(() => {
7613
+ screening = false;
7614
+ screened = null;
7615
+ });
6415
7616
  }
6416
7617
  });
6417
7618
  let lighter = null;
@@ -6426,23 +7627,20 @@ async function openPageView(page, options) {
6426
7627
  ).then(
6427
7628
  (shot) => {
6428
7629
  if (closed) return;
6429
- if (shot.length <= options.maxFrameBytes) return pacer.offer({ data: shot, ...viewport });
6430
- if (refused || !options.live()) return;
6431
- refused = true;
6432
- sent2 = "refused";
6433
- options.refuse();
7630
+ if (shot.length <= options.maxFrameBytes) return pacer.offer({ data: shot, ...viewport, at: now });
7631
+ refuse2();
6434
7632
  },
6435
7633
  () => void 0
6436
7634
  ).finally(() => {
6437
7635
  lighter = null;
6438
7636
  });
6439
7637
  };
6440
- const onFrame = (data, width, height) => {
7638
+ const onFrame = (data, width, height, at) => {
6441
7639
  if (closed || last?.equals(data)) return;
6442
7640
  last = data;
6443
7641
  if (data.length > options.maxFrameBytes) return lighten();
6444
7642
  const named = isViewSize(width, height);
6445
- pacer.offer({ data, width: named ? width : viewport.width, height: named ? height : viewport.height });
7643
+ pacer.offer({ data, width: named ? width : viewport.width, height: named ? height : viewport.height, at });
6446
7644
  };
6447
7645
  const screencast = screencastOf(page);
6448
7646
  let end = null;
@@ -6451,11 +7649,12 @@ async function openPageView(page, options) {
6451
7649
  const shoot = async () => {
6452
7650
  shots = null;
6453
7651
  if (closed || page.isClosed()) return;
7652
+ const at = Date.now();
6454
7653
  const shot = await internalCall(
6455
7654
  page,
6456
7655
  () => page.screenshot({ type: "jpeg", quality: options.quality, scale: "css", caret: "initial", timeout: 5e3 })
6457
7656
  ).catch(() => null);
6458
- if (shot) onFrame(shot, viewport.width, viewport.height);
7657
+ if (shot) onFrame(shot, viewport.width, viewport.height, at);
6459
7658
  if (!closed) {
6460
7659
  shots = setTimeout(() => void shoot(), options.shotMs);
6461
7660
  shots.unref?.();
@@ -6488,7 +7687,9 @@ async function openPageView(page, options) {
6488
7687
  size: options.size(viewport),
6489
7688
  quality: options.quality,
6490
7689
  onFrame: (frame) => {
6491
- onFrame(frame.data, frame.viewportWidth, frame.viewportHeight);
7690
+ const now = Date.now();
7691
+ const at = typeof frame.timestamp === "number" && Number.isFinite(frame.timestamp) ? Math.min(frame.timestamp, now) - SCREENCAST_LAG_MS : Number.NEGATIVE_INFINITY;
7692
+ onFrame(frame.data, frame.viewportWidth, frame.viewportHeight, at);
6492
7693
  return acks.next();
6493
7694
  }
6494
7695
  })
@@ -6512,9 +7713,22 @@ async function openPageView(page, options) {
6512
7713
  },
6513
7714
  resend: () => {
6514
7715
  if (closed || !sent2 || !options.live()) return;
6515
- if (sent2 === "refused") options.refuse();
7716
+ if ("refused" in sent2) options.refuse(sent2.refused);
6516
7717
  else options.send(sent2);
6517
7718
  },
7719
+ refresh: () => {
7720
+ if (closed) return;
7721
+ sent2 = null;
7722
+ last = null;
7723
+ const at = Date.now();
7724
+ void internalCall(
7725
+ page,
7726
+ () => page.screenshot({ type: "jpeg", quality: options.quality, scale: "css", caret: "initial", timeout: 5e3 })
7727
+ ).then(
7728
+ (shot) => onFrame(shot, viewport.width, viewport.height, at),
7729
+ () => void 0
7730
+ );
7731
+ },
6518
7732
  close: async () => {
6519
7733
  closed = true;
6520
7734
  sent2 = null;
@@ -6522,7 +7736,7 @@ async function openPageView(page, options) {
6522
7736
  pacer.close();
6523
7737
  if (shots) clearTimeout(shots);
6524
7738
  holders.delete(holder);
6525
- await lighter;
7739
+ await Promise.all([lighter, screened]);
6526
7740
  const stop = end;
6527
7741
  end = null;
6528
7742
  if (stop && !page.isClosed()) await stop().catch(() => void 0);
@@ -6540,6 +7754,7 @@ var MAX_EVENT_TEXT = 64 * 1024;
6540
7754
  var MAX_STATES_WAITING = 8;
6541
7755
  var LIGHT_QUALITY = 30;
6542
7756
  var SHOT_MS = 1e3;
7757
+ var LOG_SPACING_MS = Math.ceil(1e3 / LIVE_CALL_LOGS_PER_SECOND);
6543
7758
  var VIEW_END_MS = 1e3;
6544
7759
  var GIVE_UP = /* @__PURE__ */ new Set([401, 403, 404, 410]);
6545
7760
  var TOO_HEAVY = `This page is too heavy for the live view: each image of it is over ${MAX_LIVE_FRAME / 1024} KB, a lighter one included.`;
@@ -6612,7 +7827,8 @@ function openLiveView(worker, env = process.env, ci = detectCi(env)) {
6612
7827
  address,
6613
7828
  id: { shard: resolveShardInfo(worker.config, env)?.current ?? null, worker: worker.workerIndex },
6614
7829
  client,
6615
- agent: new client.Agent({ keepAlive: true, maxSockets: 2 }),
7830
+ // The stream, and a frame, a call log and a stop or an end in flight at once: none waits behind another.
7831
+ agent: new client.Agent({ keepAlive: true, maxSockets: 4 }),
6616
7832
  stream: null,
6617
7833
  timer: null,
6618
7834
  retries: 0,
@@ -6620,13 +7836,20 @@ function openLiveView(worker, env = process.env, ci = detectCi(env)) {
6620
7836
  ended: false,
6621
7837
  refused: null,
6622
7838
  sharing: ci,
7839
+ ci,
6623
7840
  lost: null,
6624
7841
  answered: null,
6625
7842
  viewers: 0,
6626
7843
  states: Promise.resolve(),
6627
7844
  statesWaiting: 0,
6628
7845
  stop: null,
6629
- posting: false
7846
+ posting: false,
7847
+ log: null,
7848
+ logPosting: false,
7849
+ logSentAt: 0,
7850
+ logTimer: null,
7851
+ logRefused: false,
7852
+ masks: []
6630
7853
  };
6631
7854
  if (ci) connect(link);
6632
7855
  changed();
@@ -6676,9 +7899,9 @@ async function stopSharing() {
6676
7899
  own.viewers = 0;
6677
7900
  changed();
6678
7901
  }
6679
- function liveViewTestBegan(title, call) {
7902
+ function liveViewTestBegan(title, call, mayPause2 = false) {
6680
7903
  if (!link) return;
6681
- running = { title, page: null, call };
7904
+ running = { title, page: null, call, mayPause: mayPause2, began: Date.now() };
6682
7905
  }
6683
7906
  function liveViewPage(page) {
6684
7907
  if (!link || !running || running.page) return;
@@ -6704,7 +7927,7 @@ function liveViewStopped(stop) {
6704
7927
  };
6705
7928
  }
6706
7929
  function hideCallSecrets(call) {
6707
- return { ...call, title: hideSecretsInText(call.title) };
7930
+ return { ...call, title: hideSecretsInText(hideTypedText(call.title)) };
6708
7931
  }
6709
7932
  function postState(own, message) {
6710
7933
  if (!active(own) || own.statesWaiting >= MAX_STATES_WAITING) return;
@@ -6772,7 +7995,8 @@ function connect(own) {
6772
7995
  text = text.slice(end + 2);
6773
7996
  const data = block.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
6774
7997
  const message = data ? parseInstanceToWorker(data) : null;
6775
- if (message) setViewers(own, message.count);
7998
+ if (message?.type === "masks") setMasks(own, message.locators);
7999
+ else if (message) setViewers(own, message.count);
6776
8000
  }
6777
8001
  });
6778
8002
  response.on("error", () => drop(null));
@@ -6812,11 +8036,19 @@ function setViewers(own, count) {
6812
8036
  return;
6813
8037
  }
6814
8038
  if (view) {
6815
- if (count > before) void view.opened.then((opened) => opened?.resend());
8039
+ if (count > before) {
8040
+ void view.opened.then((opened) => opened?.resend());
8041
+ if (own.log) postLog(own, own.log);
8042
+ }
6816
8043
  return;
6817
8044
  }
6818
8045
  startView();
6819
8046
  }
8047
+ function setMasks(own, locators) {
8048
+ if (JSON.stringify(locators) === JSON.stringify(own.masks)) return;
8049
+ own.masks = locators;
8050
+ if (own === link) void view?.opened.then((opened) => opened?.refresh());
8051
+ }
6820
8052
  function startView() {
6821
8053
  const own = link;
6822
8054
  const page = running?.page ?? null;
@@ -6826,6 +8058,11 @@ function startView() {
6826
8058
  return;
6827
8059
  }
6828
8060
  const live = () => view?.page === page && link === own && active(own) && own.viewers > 0;
8061
+ const mask = maskSecretFields(page, {
8062
+ masks: () => own.masks,
8063
+ quality: LIVE_FRAME_QUALITY,
8064
+ maxBytes: MAX_LIVE_FRAME
8065
+ });
6829
8066
  const opened = openPageView(page, {
6830
8067
  size: (viewport) => fitViewSize(viewport, LIVE_FRAME_WIDTH, LIVE_FRAME_HEIGHT),
6831
8068
  quality: LIVE_FRAME_QUALITY,
@@ -6834,28 +8071,39 @@ function startView() {
6834
8071
  maxFrameBytes: MAX_LIVE_FRAME,
6835
8072
  lightQuality: LIGHT_QUALITY,
6836
8073
  shotMs: SHOT_MS,
6837
- busy: () => own.posting,
8074
+ busy: () => own.posting || mask.resting,
6838
8075
  live,
8076
+ screen: (frame) => mask.screen(frame),
6839
8077
  send: (frame) => postFrame(own, frame),
6840
- refuse: () => void post(own, { type: "frame", ...own.id, refused: TOO_HEAVY })
8078
+ refuse: (why) => void post(own, { type: "frame", ...own.id, refused: why ?? TOO_HEAVY })
6841
8079
  }).catch(() => null);
6842
8080
  const onClose = () => {
6843
8081
  if (view?.page === page) void stopView();
6844
8082
  };
6845
8083
  page.once("close", onClose);
6846
- view = { page, opened, onClose };
8084
+ const following = own.ci && running && !running.mayPause && !own.logRefused ? followCallLog(page, running.began, (log) => {
8085
+ if (live()) postLog(own, log);
8086
+ }).catch(() => null) : null;
8087
+ view = { page, opened, onClose, following };
6847
8088
  }
6848
8089
  async function stopView() {
6849
8090
  const shown2 = view;
6850
8091
  view = null;
6851
8092
  if (!shown2) return;
6852
8093
  shown2.page.off("close", shown2.onClose);
8094
+ void shown2.following?.then((stop) => stop?.());
8095
+ const own = link;
8096
+ if (own) {
8097
+ own.log = null;
8098
+ if (own.logTimer) clearTimeout(own.logTimer);
8099
+ own.logTimer = null;
8100
+ }
6853
8101
  const closed = shown2.opened.then((opened) => opened?.close());
6854
8102
  let timer;
6855
8103
  await Promise.race([
6856
8104
  closed.catch(() => void 0),
6857
- new Promise((resolve5) => {
6858
- timer = setTimeout(resolve5, VIEW_END_MS);
8105
+ new Promise((resolve6) => {
8106
+ timer = setTimeout(resolve6, VIEW_END_MS);
6859
8107
  timer.unref?.();
6860
8108
  })
6861
8109
  ]);
@@ -6876,19 +8124,47 @@ function postFrame(own, frame) {
6876
8124
  own.posting = false;
6877
8125
  });
6878
8126
  }
8127
+ function postLog(own, log) {
8128
+ own.log = log;
8129
+ nextLog(own);
8130
+ }
8131
+ function nextLog(own) {
8132
+ if (own.logPosting || own.logTimer) return;
8133
+ const wait = LOG_SPACING_MS - (Date.now() - own.logSentAt);
8134
+ if (wait > 0) {
8135
+ own.logTimer = setTimeout(() => {
8136
+ own.logTimer = null;
8137
+ nextLog(own);
8138
+ }, wait);
8139
+ own.logTimer.unref?.();
8140
+ return;
8141
+ }
8142
+ const log = own.log;
8143
+ if (!active(own) || !view || !log || own.logRefused) return;
8144
+ own.logPosting = true;
8145
+ own.logSentAt = Date.now();
8146
+ let again = false;
8147
+ void post(own, { type: "call-log", ...own.id, log, test: running?.title ?? null }).then((status) => {
8148
+ if (status === 400) own.logRefused = true;
8149
+ again = status === 429;
8150
+ }).catch(() => void 0).finally(() => {
8151
+ own.logPosting = false;
8152
+ if (own.log && (own.log !== log || again)) nextLog(own);
8153
+ });
8154
+ }
6879
8155
  function post(own, message) {
6880
8156
  return active(own) ? send(own, message) : Promise.resolve(null);
6881
8157
  }
6882
8158
  function send(own, message) {
6883
8159
  if (own.ended || own.refused !== null) return Promise.resolve(null);
6884
8160
  const body = JSON.stringify(message);
6885
- return new Promise((resolve5) => {
8161
+ return new Promise((resolve6) => {
6886
8162
  let settled = false;
6887
8163
  const settle = (status) => {
6888
8164
  if (settled) return;
6889
8165
  settled = true;
6890
8166
  if (status !== null && GIVE_UP.has(status)) refuse(own, status);
6891
- resolve5(status);
8167
+ resolve6(status);
6892
8168
  };
6893
8169
  const request = own.client.request(own.address.url, {
6894
8170
  method: "POST",
@@ -6915,7 +8191,6 @@ function send(own, message) {
6915
8191
  // src/internal/capture/run-channel.ts
6916
8192
  var CONNECT_MS = 2e3;
6917
8193
  var BAR_HIDDEN2 = "#__piwi-pause-bar { display: none !important; }";
6918
- var OUTLINE_STYLE = "outline: 2px dashed #a78bfa; outline-offset: 2px; background: rgba(167, 139, 250, 0.15);";
6919
8194
  var WENT_ON = "The test went on.";
6920
8195
  var MAX_FRAME_BACKLOG = 1024 * 1024;
6921
8196
  var SHOT_MS2 = 500;
@@ -6923,6 +8198,7 @@ var LIGHT_QUALITY2 = 30;
6923
8198
  var TOO_HEAVY2 = `This page is too heavy for the live view: each image of it is over ${MAX_VIEW_FRAME / 1024} KB, a lighter one included. The image of the stop still shows it.`;
6924
8199
  var VIEW_END_MS2 = 1e3;
6925
8200
  var PAGE_ANSWER_MS = 1e4;
8201
+ var OUTLINE_MS = 2e3;
6926
8202
  var NO_ANSWER = "The page did not answer in time.";
6927
8203
  var LATE_ACT = "The page did not answer in time: the action may still take effect, and is told when it does.";
6928
8204
  var MAX_INPUT_WAITING = 4;
@@ -6962,11 +8238,12 @@ var sharedHere = false;
6962
8238
  var liveSaid = "";
6963
8239
  var unhearLive = null;
6964
8240
  var NO_AGENT_PAGE = "This stop has no page an agent can read: its call does not name one among its context's pages.";
6965
- function workerTakes(env = process.env) {
8241
+ function workerTakes(env = process.env, playwright) {
6966
8242
  const pairing = !!env[PIWI_LOCAL_DEBUG_ENV.editorSend];
6967
8243
  const recorder = parseRecordChannel(env[RECORD_CHANNEL_ENV]) !== null;
8244
+ const boxes = playwright === void 0 || playwrightVersionAtLeast(playwright, PICK_AT_SINCE);
6968
8245
  return RUN_TAKES.filter(
6969
- (take) => take === "pick" ? pairing : take === "record" || take === "assert" ? recorder : true
8246
+ (take2) => take2 === "pick" ? pairing : take2 === "record" || take2 === "assert" ? recorder : take2 === "pick-at" ? boxes : true
6970
8247
  );
6971
8248
  }
6972
8249
  async function openRunChannel(worker, handlers, env = process.env) {
@@ -6975,15 +8252,15 @@ async function openRunChannel(worker, handlers, env = process.env) {
6975
8252
  if (socket || !channel || !ref || !/^[\w-]{1,64}$/.test(ref)) return false;
6976
8253
  const opening = net.connect(channel.path);
6977
8254
  opening.setEncoding("utf8");
6978
- const opened = await new Promise((resolve5) => {
6979
- const timer = setTimeout(() => resolve5(false), CONNECT_MS);
8255
+ const opened = await new Promise((resolve6) => {
8256
+ const timer = setTimeout(() => resolve6(false), CONNECT_MS);
6980
8257
  opening.once("connect", () => {
6981
8258
  clearTimeout(timer);
6982
- resolve5(true);
8259
+ resolve6(true);
6983
8260
  });
6984
8261
  opening.once("error", () => {
6985
8262
  clearTimeout(timer);
6986
- resolve5(false);
8263
+ resolve6(false);
6987
8264
  });
6988
8265
  });
6989
8266
  if (!opened || opening.destroyed) {
@@ -7026,8 +8303,10 @@ async function openRunChannel(worker, handlers, env = process.env) {
7026
8303
  pid: process.pid,
7027
8304
  playwright: worker.config.version,
7028
8305
  reporter: getReporterVersion(),
7029
- takes: workerTakes(env),
7030
- holds: [...RUN_HOLDS]
8306
+ takes: workerTakes(env, worker.config.version),
8307
+ holds: [...RUN_HOLDS],
8308
+ // A run the reporter follows from outside the editor, which its own test runner started.
8309
+ ...ref.startsWith(TERMINAL_REF_PREFIX) && startedByTestRunner(env) ? { runner: true } : {}
7031
8310
  });
7032
8311
  liveSaid = "";
7033
8312
  tellLive();
@@ -7100,7 +8379,7 @@ async function unbind() {
7100
8379
  const shared = bound?.browser;
7101
8380
  bound = null;
7102
8381
  if (shared?.isConnected()) {
7103
- await within2(
8382
+ await within3(
7104
8383
  internalCall(shared, () => bindBrowser(shared, runName, process.cwd(), false)),
7105
8384
  VIEW_END_MS2
7106
8385
  );
@@ -7160,7 +8439,7 @@ function viewEnded(stop) {
7160
8439
  else viewEnds.add(() => ended.abort());
7161
8440
  return ended.signal;
7162
8441
  }
7163
- async function within2(run, ms) {
8442
+ async function within3(run, ms) {
7164
8443
  await answerWithin(run, ms, void 0);
7165
8444
  }
7166
8445
  async function answerWithin(run, ms, late) {
@@ -7168,20 +8447,20 @@ async function answerWithin(run, ms, late) {
7168
8447
  try {
7169
8448
  return await Promise.race([
7170
8449
  run.catch(() => late),
7171
- new Promise((resolve5) => timer = setTimeout(() => resolve5(late), ms))
8450
+ new Promise((resolve6) => timer = setTimeout(() => resolve6(late), ms))
7172
8451
  ]);
7173
8452
  } finally {
7174
8453
  clearTimeout(timer);
7175
8454
  }
7176
8455
  }
7177
8456
  async function endView(stop, page) {
7178
- if (viewStarting?.stop === stop) await within2(viewStarting.started, VIEW_END_MS2);
8457
+ if (viewStarting?.stop === stop) await within3(viewStarting.started, VIEW_END_MS2);
7179
8458
  if (view2?.stop === stop) await stopView2();
7180
8459
  const own = input;
7181
8460
  input = freshInput();
7182
- await within2(own.playing, VIEW_END_MS2);
8461
+ await within3(own.playing, VIEW_END_MS2);
7183
8462
  if (page && !page.isClosed() && (own.buttons.size || own.keys.size)) {
7184
- await within2(
8463
+ await within3(
7185
8464
  internalCall(page, async () => {
7186
8465
  for (const button of own.buttons) await page.mouse.up({ button });
7187
8466
  for (const key of own.keys) await page.keyboard.up(key);
@@ -7195,7 +8474,7 @@ async function stopView2() {
7195
8474
  view2 = null;
7196
8475
  for (const end of viewEnds) end();
7197
8476
  viewEnds.clear();
7198
- if (shown2) await within2(shown2.close(), VIEW_END_MS2);
8477
+ if (shown2) await within3(shown2.close(), VIEW_END_MS2);
7199
8478
  }
7200
8479
  function startView2(holding) {
7201
8480
  if (view2?.stop === holding.stop) {
@@ -7215,7 +8494,7 @@ function startView2(holding) {
7215
8494
  }
7216
8495
  if (!opened) return { ok: false, message: "The page could not be shown: it closed, or does not answer." };
7217
8496
  if (held !== holding || page.isClosed()) {
7218
- await within2(opened.close(), VIEW_END_MS2);
8497
+ await within3(opened.close(), VIEW_END_MS2);
7219
8498
  return { ok: false, message: WENT_ON };
7220
8499
  }
7221
8500
  view2 = opened;
@@ -7259,7 +8538,7 @@ async function openView(page, stop) {
7259
8538
  };
7260
8539
  }
7261
8540
  async function stopViewOf(holding) {
7262
- if (viewStarting?.stop === holding.stop) await within2(viewStarting.started, VIEW_END_MS2);
8541
+ if (viewStarting?.stop === holding.stop) await within3(viewStarting.started, VIEW_END_MS2);
7263
8542
  if (view2?.stop === holding.stop) await stopView2();
7264
8543
  return { ok: true, message: "The live view is off." };
7265
8544
  }
@@ -7350,18 +8629,17 @@ async function countLocator(holding, source) {
7350
8629
  if (!locator) return { ok: false, message: `${source} is not a locator Piwi can build.`, count: null };
7351
8630
  try {
7352
8631
  const count = await internalCall(page, () => locator.count());
8632
+ let outlined = false;
7353
8633
  if (holding.bar && count > 0 && held === holding) {
7354
- const shown2 = await internalCall(page, () => locator.highlight({ style: OUTLINE_STYLE }));
7355
- const dispose = shown2?.dispose;
7356
- outline = {
7357
- stop: holding.stop,
7358
- remove: () => internalCall(page, () => typeof dispose === "function" ? dispose.call(shown2) : page.hideHighlight())
7359
- };
8634
+ const shown2 = highlightAtStop(page, locator, "count", source);
8635
+ outline = { stop: holding.stop, remove: async () => void await shown2.hide() };
8636
+ outlined = await answerWithin(shown2.shown, OUTLINE_MS, false);
7360
8637
  }
7361
8638
  return {
7362
8639
  ok: true,
7363
8640
  message: count === 0 ? "No element matches." : count === 1 ? "1 element matches." : `${count} elements match.`,
7364
- count
8641
+ count,
8642
+ outlined
7365
8643
  };
7366
8644
  } catch (error) {
7367
8645
  return { ok: false, message: `The locator could not be counted: ${errorMessage(error)}`, count: null };
@@ -7548,17 +8826,17 @@ async function imageOf(page) {
7548
8826
 
7549
8827
  // src/internal/capture/run-events.ts
7550
8828
  var begun = /* @__PURE__ */ new WeakMap();
7551
- var heard = /* @__PURE__ */ new WeakSet();
8829
+ var heard2 = /* @__PURE__ */ new WeakSet();
7552
8830
  var watched = /* @__PURE__ */ new WeakSet();
7553
- function userFile(file, cwd, windows) {
8831
+ function userFile2(file, cwd, windows) {
7554
8832
  if (!file || /[\\/]node_modules[\\/]/.test(file)) return null;
7555
- const relative6 = callSitePath(file, cwd, windows);
7556
- if (!relative6 || (windows ? path9.win32 : path9.posix).isAbsolute(relative6) || relative6.startsWith("..")) return null;
7557
- return relative6;
8833
+ const relative7 = callSitePath(file, cwd, windows);
8834
+ if (!relative7 || (windows ? path11.win32 : path11.posix).isAbsolute(relative7) || relative7.startsWith("..")) return null;
8835
+ return relative7;
7558
8836
  }
7559
8837
  function callPlace(frames, cwd = process.cwd(), windows = process.platform === "win32") {
7560
8838
  for (const frame of frames ?? []) {
7561
- const file = userFile(frame.file, cwd, windows);
8839
+ const file = userFile2(frame.file, cwd, windows);
7562
8840
  if (!file || !frame.line || frame.line < 1) continue;
7563
8841
  return { file, line: frame.line, ...frame.column && frame.column > 0 ? { column: frame.column } : {} };
7564
8842
  }
@@ -7575,9 +8853,9 @@ function errorText(error) {
7575
8853
  }
7576
8854
  function watchCalls(playwright) {
7577
8855
  const instrumentation = playwright?._instrumentation;
7578
- if (!playwright || heard.has(playwright)) return true;
8856
+ if (!playwright || heard2.has(playwright)) return true;
7579
8857
  if (!instrumentation || typeof instrumentation.addListener !== "function") return false;
7580
- heard.add(playwright);
8858
+ heard2.add(playwright);
7581
8859
  const titles = /* @__PURE__ */ new WeakMap();
7582
8860
  instrumentation.addListener({
7583
8861
  onApiCallBegin: (zone, channel) => {
@@ -7694,9 +8972,9 @@ function yamlScalar(text) {
7694
8972
  }
7695
8973
 
7696
8974
  // src/internal/capture/record-handoff.ts
7697
- var fs6 = __toESM(require("fs"));
8975
+ var fs8 = __toESM(require("fs"));
7698
8976
  var net2 = __toESM(require("net"));
7699
- var path10 = __toESM(require("path"));
8977
+ var path12 = __toESM(require("path"));
7700
8978
  var START_WAIT_MS = 6e4;
7701
8979
  var NEW_TAB_NOTICE = "A new tab opened: what you do there is not recorded yet. Record in the first tab.";
7702
8980
  var relays = /* @__PURE__ */ new WeakMap();
@@ -7716,7 +8994,7 @@ function canRecordFromHere(channel = process.env[RECORD_CHANNEL_ENV]) {
7716
8994
  function handoffPlace(location, cwd = process.cwd()) {
7717
8995
  const m = /^(.+):(\d+):\d+$/.exec(location);
7718
8996
  if (!m) return null;
7719
- return { file: path10.resolve(cwd, m[1]), line: Number(m[2]) };
8997
+ return { file: path12.resolve(cwd, m[1]), line: Number(m[2]) };
7720
8998
  }
7721
8999
  async function recordFromHere(options) {
7722
9000
  const channel = parseRecordChannel(options.channel ?? process.env[RECORD_CHANNEL_ENV]);
@@ -7726,7 +9004,7 @@ async function recordFromHere(options) {
7726
9004
  if (ended?.aborted) return "the test ended.";
7727
9005
  const use = testInfo.project?.use ?? {};
7728
9006
  const context = page.context();
7729
- return new Promise((resolve5) => {
9007
+ return new Promise((resolve6) => {
7730
9008
  const socket2 = net2.connect(channel.path);
7731
9009
  socket2.setEncoding("utf8");
7732
9010
  const answers = /* @__PURE__ */ new Map();
@@ -7787,7 +9065,7 @@ async function recordFromHere(options) {
7787
9065
  page.off("crash", onGone);
7788
9066
  ended?.removeEventListener("abort", onEnded);
7789
9067
  socket2.end();
7790
- resolve5(recording ? null : said);
9068
+ resolve6(recording ? null : said);
7791
9069
  };
7792
9070
  const relayed = (source, payload) => new Promise((answer) => {
7793
9071
  const call = ++calls;
@@ -7819,7 +9097,7 @@ async function recordFromHere(options) {
7819
9097
  if (typeof initScript?.dispose !== "function") relay.lingering = true;
7820
9098
  }
7821
9099
  if (settled) return release();
7822
- await page.evaluate(fs6.readFileSync(bundle, "utf-8"));
9100
+ await page.evaluate(fs8.readFileSync(bundle, "utf-8"));
7823
9101
  if (settled) return release();
7824
9102
  recording = true;
7825
9103
  clearTimeout(startWait);
@@ -7887,76 +9165,168 @@ function cssCoverageInWorker() {
7887
9165
  }
7888
9166
  function browserCoverageInWorker() {
7889
9167
  const browser = process.env[PIWI_ENV_KEYS.coverageBrowser];
7890
- return process.env[PIWI_ENV_KEYS.captureCodeReach] === "true" || browser === "files" || browser === "functions";
9168
+ return process.env[PIWI_ENV_KEYS.captureCodeReach] === "true" || browser === "files" || browser === "functions" || browser === "lines";
7891
9169
  }
7892
9170
  function browserFunctionsInWorker() {
7893
- return process.env[PIWI_ENV_KEYS.coverageBrowser] === "functions";
9171
+ const browser = process.env[PIWI_ENV_KEYS.coverageBrowser];
9172
+ return browser === "functions" || browser === "lines";
9173
+ }
9174
+ function browserLinesInWorker() {
9175
+ return process.env[PIWI_ENV_KEYS.coverageBrowser] === "lines";
7894
9176
  }
7895
- function browserFunctionCoverage(files) {
9177
+ function browserFunctionCoverage(files, lines) {
9178
+ const entries = [...files].map(([path19, functions]) => ({ path: path19, functions: normalizeFunctionRanges(functions) }));
9179
+ let budget = MAX_COVERAGE_RANGES - entries.reduce((n, entry) => n + entry.functions.length, 0);
9180
+ let incomplete = false;
7896
9181
  return sanitizeCoverage({
7897
9182
  v: 1,
7898
- files: [...files].map(([path16, functions]) => ({ path: path16, runtime: "browser", functions }))
9183
+ files: entries.map(({ path: path19, functions }) => {
9184
+ const ran = normalizeLineRanges(lines?.get(path19) ?? []);
9185
+ if (ran.length === 0) return { path: path19, runtime: "browser", functions };
9186
+ if (ran.length > budget) {
9187
+ incomplete = true;
9188
+ return { path: path19, runtime: "browser", functions };
9189
+ }
9190
+ budget -= ran.length;
9191
+ return { path: path19, runtime: "browser", functions, lines: ran };
9192
+ }),
9193
+ ...incomplete ? { incomplete: true } : {}
7899
9194
  });
7900
9195
  }
7901
- function newKnownFunctions(known, sent2) {
9196
+ function newRangeParts(known, sent2, normalize2) {
7902
9197
  const parts = [];
7903
9198
  let files = [];
7904
9199
  let budget = MAX_COVERAGE_RANGES;
7905
9200
  const close = () => {
7906
- if (files.length > 0) parts.push({ v: 1, files: files.sort((a, b) => a.path < b.path ? -1 : 1) });
9201
+ if (files.length > 0) parts.push(files.sort((a, b) => a.path < b.path ? -1 : 1));
7907
9202
  files = [];
7908
9203
  budget = MAX_COVERAGE_RANGES;
7909
9204
  };
7910
9205
  for (const [raw, ranges] of known) {
7911
- const path16 = normalizeCoveragePath(raw);
7912
- if (path16 === null) continue;
7913
- let named = sent2.get(path16);
7914
- let fresh = normalizeFunctionRanges(ranges).filter((range) => !named?.has(`${range[0]}:${range[1]}`));
9206
+ const path19 = normalizeCoveragePath(raw);
9207
+ if (path19 === null) continue;
9208
+ let named = sent2.get(path19);
9209
+ let fresh = normalize2(ranges).filter((range) => !named?.has(`${range[0]}:${range[1]}`));
7915
9210
  if (fresh.length === 0) continue;
7916
- if (!named) sent2.set(path16, named = /* @__PURE__ */ new Set());
9211
+ if (!named) sent2.set(path19, named = /* @__PURE__ */ new Set());
7917
9212
  for (const range of fresh) named.add(`${range[0]}:${range[1]}`);
7918
9213
  while (fresh.length > 0) {
7919
9214
  if (budget === 0 || files.length >= MAX_COVERAGE_FILES) close();
7920
9215
  const part = fresh.slice(0, budget);
7921
9216
  fresh = fresh.slice(part.length);
7922
9217
  budget -= part.length;
7923
- files.push({ path: path16, allFunctions: part });
9218
+ files.push({ path: path19, ranges: part });
7924
9219
  }
7925
9220
  }
7926
9221
  close();
7927
9222
  return parts;
7928
9223
  }
9224
+ function newKnownFunctions(known, sent2) {
9225
+ return newRangeParts(known, sent2, normalizeFunctionRanges).map((files) => ({
9226
+ v: 1,
9227
+ files: files.map(({ path: path19, ranges }) => ({ path: path19, allFunctions: ranges }))
9228
+ }));
9229
+ }
9230
+ function newBrowserLines(executable, lines, sentExecutable, sentLines) {
9231
+ return [
9232
+ ...newRangeParts(executable, sentExecutable, normalizeLineRanges).map((files) => ({
9233
+ v: 1,
9234
+ files: files.map(({ path: path19, ranges }) => ({ path: path19, executable: ranges }))
9235
+ })),
9236
+ ...newRangeParts(lines, sentLines, normalizeLineRanges).map((files) => ({
9237
+ v: 1,
9238
+ files: files.map(({ path: path19, ranges }) => ({ path: path19, lines: ranges }))
9239
+ }))
9240
+ ];
9241
+ }
7929
9242
  function serverCoverageInWorker() {
7930
9243
  return isServerGranularity(process.env[PIWI_ENV_KEYS.coverageServer]);
7931
9244
  }
7932
9245
 
7933
9246
  // src/internal/support/aria-sampling.ts
7934
- var path11 = __toESM(require("path"));
7935
- var os3 = __toESM(require("os"));
7936
- var fs7 = __toESM(require("fs"));
9247
+ var path14 = __toESM(require("path"));
9248
+ var fs10 = __toESM(require("fs"));
7937
9249
 
7938
9250
  // src/internal/support/instance-id.ts
7939
9251
  var crypto2 = __toESM(require("crypto"));
7940
- var os2 = __toESM(require("os"));
9252
+ var os3 = __toESM(require("os"));
7941
9253
  function hashForProject(projectName) {
7942
9254
  return crypto2.createHash("sha1").update(projectName).digest("hex").slice(0, 16);
7943
9255
  }
7944
9256
 
9257
+ // src/internal/support/private-file.ts
9258
+ var crypto3 = __toESM(require("crypto"));
9259
+ var fs9 = __toESM(require("fs"));
9260
+ var os4 = __toESM(require("os"));
9261
+ var path13 = __toESM(require("path"));
9262
+ function privateTempDir() {
9263
+ if (process.platform !== "win32") return os4.tmpdir();
9264
+ const dir = path13.join(process.env.LOCALAPPDATA || path13.join(os4.homedir(), "AppData", "Local"), "piwi", "tmp");
9265
+ try {
9266
+ fs9.mkdirSync(dir, { recursive: true });
9267
+ } catch {
9268
+ }
9269
+ return dir;
9270
+ }
9271
+ var NO_FOLLOW = fs9.constants.O_NOFOLLOW ?? 0;
9272
+ var NO_WAIT = fs9.constants.O_NONBLOCK ?? 0;
9273
+ function untrustedReason(stat) {
9274
+ if (stat.isSymbolicLink()) return "it is a symbolic link";
9275
+ if (!stat.isFile()) return "it is not a regular file";
9276
+ if (typeof process.getuid === "function") {
9277
+ if (stat.uid !== process.getuid()) return "another user owns it";
9278
+ if (stat.mode & 18) return "other users may write to it";
9279
+ if (stat.nlink > 1) return "it has another name";
9280
+ }
9281
+ return null;
9282
+ }
9283
+ function appendPrivateFile(file, text) {
9284
+ const found = fs9.lstatSync(file, { throwIfNoEntry: false });
9285
+ const refused = found && untrustedReason(found);
9286
+ if (refused) throw new Error(`${file} is not written: ${refused}`);
9287
+ const fd = fs9.openSync(
9288
+ file,
9289
+ fs9.constants.O_WRONLY | fs9.constants.O_APPEND | fs9.constants.O_CREAT | NO_FOLLOW | NO_WAIT,
9290
+ 384
9291
+ );
9292
+ try {
9293
+ const reason = untrustedReason(fs9.fstatSync(fd));
9294
+ if (reason) throw new Error(`${file} is not written: ${reason}`);
9295
+ fs9.appendFileSync(fd, text, "utf8");
9296
+ } finally {
9297
+ fs9.closeSync(fd);
9298
+ }
9299
+ }
9300
+ function readPrivateFile(file) {
9301
+ const found = fs9.lstatSync(file, { throwIfNoEntry: false });
9302
+ if (!found) return null;
9303
+ const reason = untrustedReason(found);
9304
+ if (reason) return { untrusted: reason };
9305
+ const fd = fs9.openSync(file, fs9.constants.O_RDONLY | NO_FOLLOW | NO_WAIT);
9306
+ try {
9307
+ const opened = untrustedReason(fs9.fstatSync(fd));
9308
+ if (opened) return { untrusted: opened };
9309
+ return { text: fs9.readFileSync(fd, "utf8") };
9310
+ } finally {
9311
+ fs9.closeSync(fd);
9312
+ }
9313
+ }
9314
+
7945
9315
  // src/internal/support/aria-sampling.ts
7946
9316
  function ariaSampleIdentity(filePath2, title) {
7947
9317
  return `${filePath2}\0${title}`;
7948
9318
  }
7949
9319
  function getAriaSampleFilePath(projectName) {
7950
- return path11.join(os3.tmpdir(), `piwi-dashboard-aria-sample-${hashForProject(projectName)}.json`);
9320
+ return path14.join(privateTempDir(), `piwi-dashboard-aria-sample-${hashForProject(projectName)}.json`);
7951
9321
  }
7952
9322
  var cachedSets = /* @__PURE__ */ new Map();
7953
9323
  function loadAriaSampleSet(projectName) {
7954
9324
  if (cachedSets.has(projectName)) return cachedSets.get(projectName);
7955
9325
  let set = null;
7956
9326
  try {
7957
- const raw = fs7.readFileSync(getAriaSampleFilePath(projectName), "utf8");
7958
- const parsed2 = JSON.parse(raw);
7959
- if (parsed2.projectName === projectName && Array.isArray(parsed2.identities)) {
9327
+ const read = readPrivateFile(getAriaSampleFilePath(projectName));
9328
+ const parsed2 = read && "text" in read ? JSON.parse(read.text) : null;
9329
+ if (parsed2?.projectName === projectName && Array.isArray(parsed2.identities)) {
7960
9330
  set = new Set(parsed2.identities.filter((x) => typeof x === "string"));
7961
9331
  }
7962
9332
  } catch {
@@ -7976,9 +9346,9 @@ function isDueForAriaSample(testInfo) {
7976
9346
  }
7977
9347
 
7978
9348
  // src/internal/capture/code-reach.ts
7979
- var crypto3 = __toESM(require("crypto"));
7980
- var fs8 = __toESM(require("fs"));
7981
- var path12 = __toESM(require("path"));
9349
+ var crypto4 = __toESM(require("crypto"));
9350
+ var fs11 = __toESM(require("fs"));
9351
+ var path15 = __toESM(require("path"));
7982
9352
  var import_node_child_process = require("child_process");
7983
9353
  var MAX_MAP_BYTES = 20 * 1024 * 1024;
7984
9354
  var MAP_TIMEOUT_MS = 5e3;
@@ -8021,18 +9391,18 @@ function repositoryRoot(from) {
8021
9391
  }).trim();
8022
9392
  } catch {
8023
9393
  }
8024
- cachedRepoRoot = { from, root: path12.resolve(root) };
9394
+ cachedRepoRoot = { from, root: path15.resolve(root) };
8025
9395
  return cachedRepoRoot.root;
8026
9396
  }
8027
9397
  function codeReachRoots(configDir, configured) {
8028
9398
  const repoRoot = repositoryRoot(configDir);
8029
- const resolve5 = (dirs) => (Array.isArray(dirs) ? dirs : dirs ? [dirs] : []).filter(Boolean).map((r) => path12.resolve(configDir, r));
8030
- const global = Array.isArray(configured) ? resolve5(configured) : resolve5(configured?.["*"]);
9399
+ const resolve6 = (dirs) => (Array.isArray(dirs) ? dirs : dirs ? [dirs] : []).filter(Boolean).map((r) => path15.resolve(configDir, r));
9400
+ const global = Array.isArray(configured) ? resolve6(configured) : resolve6(configured?.["*"]);
8031
9401
  const byOrigin = /* @__PURE__ */ new Map();
8032
9402
  if (configured && !Array.isArray(configured)) {
8033
9403
  for (const [key, dirs] of Object.entries(configured)) {
8034
9404
  const origin = key === "*" ? null : originOf2(key);
8035
- const resolved = resolve5(dirs);
9405
+ const resolved = resolve6(dirs);
8036
9406
  if (origin && resolved.length) byOrigin.set(origin, resolved);
8037
9407
  }
8038
9408
  }
@@ -8055,7 +9425,7 @@ function scriptRoots(roots, scriptUrl, pageUrl) {
8055
9425
  }
8056
9426
  function isFile(file) {
8057
9427
  try {
8058
- return fs8.statSync(file).isFile();
9428
+ return fs11.statSync(file).isFile();
8059
9429
  } catch {
8060
9430
  return false;
8061
9431
  }
@@ -8063,10 +9433,10 @@ function isFile(file) {
8063
9433
  function resolveSourcePath(source, roots) {
8064
9434
  const normalized = normalizeSourcePath(source);
8065
9435
  if (!normalized || /(?:^|\/)node_modules\//.test(normalized)) return null;
8066
- if (path12.isAbsolute(normalized) && isFile(normalized)) return path12.resolve(normalized);
8067
- const relative6 = normalized.replace(/^\/+/, "");
9436
+ if (path15.isAbsolute(normalized) && isFile(normalized)) return path15.resolve(normalized);
9437
+ const relative7 = normalized.replace(/^\/+/, "");
8068
9438
  for (const root of roots) {
8069
- const candidate = path12.resolve(root, relative6);
9439
+ const candidate = path15.resolve(root, relative7);
8070
9440
  if (isFile(candidate)) return candidate;
8071
9441
  }
8072
9442
  return null;
@@ -8098,10 +9468,18 @@ function fileForUrl(url, roots, bases) {
8098
9468
  return file;
8099
9469
  }
8100
9470
  function relativeToRepo(file, repoRoot) {
8101
- return path12.relative(repoRoot, file).split(path12.sep).join("/");
9471
+ return path15.relative(repoRoot, file).split(path15.sep).join("/");
9472
+ }
9473
+ var SERVED_AS_WRITTEN_PARAMS = /* @__PURE__ */ new Set(["t", "v", "import"]);
9474
+ function servedAsWritten(url) {
9475
+ try {
9476
+ return [...new URL(url).searchParams.keys()].every((key) => SERVED_AS_WRITTEN_PARAMS.has(key));
9477
+ } catch {
9478
+ return false;
9479
+ }
8102
9480
  }
8103
9481
  function scriptVersion(entry) {
8104
- return entry.hash ?? crypto3.createHash("sha1").update(entry.source ?? "").digest("hex");
9482
+ return entry.hash ?? crypto4.createHash("sha1").update(entry.source ?? "").digest("hex");
8105
9483
  }
8106
9484
  async function loadMap(entry, fetchMap) {
8107
9485
  const ref = entry.source ? sourceMappingUrl(entry.source) : null;
@@ -8138,7 +9516,8 @@ async function resolveScript(entry, roots, bases, fetchMap) {
8138
9516
  const file = fileForUrl(entry.url, roots, bases);
8139
9517
  const lookup = await loadMap(entry, fetchMap);
8140
9518
  let resolution;
8141
- const text = entry.source === void 0 ? void 0 : scriptText(entry.source);
9519
+ const code = !!file && !lookup && browserLinesInWorker() && servedAsWritten(entry.url);
9520
+ const text = entry.source === void 0 ? void 0 : scriptText(entry.source, { code });
8142
9521
  if (file) resolution = { kind: "file", file, lookup, text };
8143
9522
  else resolution = lookup ? { kind: "map", lookup, files: [], text } : { kind: "none" };
8144
9523
  if (text) scriptCache.set(entry.url, version, resolution);
@@ -8151,20 +9530,26 @@ async function resolveCodeReach(entries, roots, fetchMap, pageUrl) {
8151
9530
  return finalizeCodeReach((await resolveReach(entries, roots, fetchMap, pageUrl)).keys());
8152
9531
  }
8153
9532
  async function resolveCodeReachFunctions(entries, roots, fetchMap, pageUrl, options = {}) {
8154
- return resolveFunctions(entries, roots, fetchMap, pageUrl, options.known === true);
9533
+ return resolveFunctions(entries, roots, fetchMap, pageUrl, options.known === true, options.lines === true);
8155
9534
  }
8156
9535
  async function resolveReach(entries, roots, fetchMap, pageUrl) {
8157
- return (await resolveFunctions(entries, roots, fetchMap, pageUrl, false)).reached;
9536
+ return (await resolveFunctions(entries, roots, fetchMap, pageUrl, false, false)).reached;
8158
9537
  }
8159
9538
  var knownCache = new LatestByUrl();
8160
- async function resolveFunctions(entries, roots, fetchMap, pageUrl, withKnown) {
9539
+ async function resolveFunctions(entries, roots, fetchMap, pageUrl, withKnown, withLines) {
8161
9540
  const files = /* @__PURE__ */ new Map();
8162
9541
  const known = /* @__PURE__ */ new Map();
9542
+ const lines = /* @__PURE__ */ new Map();
9543
+ const executable = /* @__PURE__ */ new Map();
9544
+ const addLines = (into, file, ranges) => {
9545
+ const path19 = relativeToRepo(file, roots.repoRoot);
9546
+ into.set(path19, normalizeLineRanges([...into.get(path19) ?? [], ...ranges]));
9547
+ };
8163
9548
  const addTo = (into, file, functions) => {
8164
- const path16 = relativeToRepo(file, roots.repoRoot);
8165
- const listed = into.get(path16);
9549
+ const path19 = relativeToRepo(file, roots.repoRoot);
9550
+ const listed = into.get(path19);
8166
9551
  if (listed) listed.push(...functions);
8167
- else into.set(path16, [...functions]);
9552
+ else into.set(path19, [...functions]);
8168
9553
  };
8169
9554
  const add2 = (file, functions) => addTo(files, file, functions);
8170
9555
  const bases = viteBases(entries);
@@ -8203,6 +9588,17 @@ async function resolveFunctions(entries, roots, fetchMap, pageUrl, withKnown) {
8203
9588
  if (file) add2(file, functions);
8204
9589
  }
8205
9590
  }
9591
+ const ownLines = resolution.kind === "map" || resolution.kind === "file" && (!!resolution.lookup || servedAsWritten(covered.url));
9592
+ if (withLines && covered.executed && resolution.kind !== "none" && ownLines) {
9593
+ const text = textOf3(covered, resolution);
9594
+ const lookup = resolution.lookup;
9595
+ for (const [index, sourceLines] of scriptLines(covered, covered.executed, lookup, text)) {
9596
+ const file = resolution.kind === "file" ? resolution.file : mapFile(resolution, index);
9597
+ if (!file) continue;
9598
+ addLines(executable, file, sourceLines.executable);
9599
+ addLines(lines, file, sourceLines.lines);
9600
+ }
9601
+ }
8206
9602
  if (!withKnown || resolution.kind === "none") continue;
8207
9603
  const version = scriptVersion(covered);
8208
9604
  let listed = knownCache.get(covered.url, version);
@@ -8210,8 +9606,8 @@ async function resolveFunctions(entries, roots, fetchMap, pageUrl, withKnown) {
8210
9606
  const byFile = /* @__PURE__ */ new Map();
8211
9607
  const text = textOf3(covered, resolution);
8212
9608
  if (resolution.kind === "file" && resolution.file) {
8213
- const lines = knownFunctionLines(covered, resolution.lookup, text);
8214
- const all = resolution.lookup ? [...lines.values()].flat() : lines.get(-1) ?? [];
9609
+ const lines2 = knownFunctionLines(covered, resolution.lookup, text);
9610
+ const all = resolution.lookup ? [...lines2.values()].flat() : lines2.get(-1) ?? [];
8215
9611
  if (all.length > 0) byFile.set(resolution.file, all);
8216
9612
  } else if (resolution.kind === "map") {
8217
9613
  for (const [index, functions] of knownFunctionLines(covered, resolution.lookup, text)) {
@@ -8224,7 +9620,7 @@ async function resolveFunctions(entries, roots, fetchMap, pageUrl, withKnown) {
8224
9620
  }
8225
9621
  for (const [file, functions] of listed.files) addTo(known, file, functions);
8226
9622
  }
8227
- return { reached: files, known };
9623
+ return { reached: files, known, lines, executable };
8228
9624
  }
8229
9625
  function pageMapFetcher(page) {
8230
9626
  return async (url) => {
@@ -8285,7 +9681,7 @@ function onPaused(page, capture, event) {
8285
9681
  ]) : null;
8286
9682
  if (read) {
8287
9683
  const merging = read.then(
8288
- ([coverage]) => mergeCoverageRead(capture.ran, capture.scripts, coverage, capture.keepIdle)
9684
+ ([coverage]) => mergeCoverageRead(capture.ran, capture.scripts, coverage, capture.keepIdle, capture.blocks)
8289
9685
  );
8290
9686
  capture.reading.add(merging);
8291
9687
  void merging.finally(() => capture.reading.delete(merging));
@@ -8319,8 +9715,8 @@ function onScriptParsed(page, capture, event) {
8319
9715
  var READ_WAIT_MS = 5e3;
8320
9716
  function readCoverage(page, cdp) {
8321
9717
  let timer;
8322
- const late = new Promise((resolve5) => {
8323
- timer = setTimeout(() => resolve5([]), READ_WAIT_MS);
9718
+ const late = new Promise((resolve6) => {
9719
+ timer = setTimeout(() => resolve6([]), READ_WAIT_MS);
8324
9720
  });
8325
9721
  const taken = internalCall(page, () => cdp.send("Profiler.takePreciseCoverage")).then(
8326
9722
  (answer) => answer.result,
@@ -8375,7 +9771,7 @@ async function readCssUsage(page, cdp, css) {
8375
9771
  } catch {
8376
9772
  }
8377
9773
  }
8378
- function mergeCoverageRead(ran, scripts, read, keepIdle = true) {
9774
+ function mergeCoverageRead(ran, scripts, read, keepIdle = true, blocks = false) {
8379
9775
  for (const covered of read) {
8380
9776
  const script = scripts.get(covered.scriptId);
8381
9777
  if (!script) continue;
@@ -8385,6 +9781,7 @@ function mergeCoverageRead(ran, scripts, read, keepIdle = true) {
8385
9781
  known = { script, functions: [], byRange: /* @__PURE__ */ new Map() };
8386
9782
  ran.set(key, known);
8387
9783
  }
9784
+ if (blocks) known.executed = unionOffsets(known.executed ?? [], executedOffsets(covered.functions));
8388
9785
  for (const fn of covered.functions) {
8389
9786
  const whole = fn.ranges[0];
8390
9787
  if (!whole) continue;
@@ -8395,7 +9792,7 @@ function mergeCoverageRead(ran, scripts, read, keepIdle = true) {
8395
9792
  if (whole.count > 0 && seen.ranges[0].count <= 0) seen.ranges[0].count = whole.count;
8396
9793
  continue;
8397
9794
  }
8398
- const copy = { ...fn, ranges: fn.ranges.map((r) => ({ ...r })) };
9795
+ const copy = { ...fn, ranges: [{ ...whole }] };
8399
9796
  known.byRange.set(range, copy);
8400
9797
  known.functions.push(copy);
8401
9798
  }
@@ -8411,6 +9808,7 @@ async function startCodeReach(page) {
8411
9808
  if (!isChromiumPage(page) || captures.has(page)) return false;
8412
9809
  const withCss = cssCoverageInWorker();
8413
9810
  const js = browserCoverageInWorker() || !withCss;
9811
+ const blocks = js && browserLinesInWorker();
8414
9812
  let cdp = null;
8415
9813
  try {
8416
9814
  cdp = await internalCall(page, () => page.context().newCDPSession(page));
@@ -8422,6 +9820,7 @@ async function startCodeReach(page) {
8422
9820
  sources: /* @__PURE__ */ new Map(),
8423
9821
  ran: /* @__PURE__ */ new Map(),
8424
9822
  keepIdle: browserFunctionsInWorker(),
9823
+ blocks,
8425
9824
  reading: /* @__PURE__ */ new Set(),
8426
9825
  pageUrl: page.url()
8427
9826
  };
@@ -8442,7 +9841,7 @@ async function startCodeReach(page) {
8442
9841
  capture.cdp.send("Debugger.enable"),
8443
9842
  ...js ? [
8444
9843
  capture.cdp.send("Profiler.enable"),
8445
- capture.cdp.send("Profiler.startPreciseCoverage", { callCount: false, detailed: false })
9844
+ capture.cdp.send("Profiler.startPreciseCoverage", { callCount: blocks, detailed: blocks })
8446
9845
  ] : [],
8447
9846
  // The style sheets' rule usage records nothing without the DOM and CSS domains. A failure there leaves the
8448
9847
  // scripts' coverage running.
@@ -8487,10 +9886,11 @@ async function stopPageCoverage(page) {
8487
9886
  await cdp.send("Profiler.stopPreciseCoverage");
8488
9887
  return taken.result;
8489
9888
  });
8490
- mergeCoverageRead(capture.ran, capture.scripts, last, capture.keepIdle);
9889
+ mergeCoverageRead(capture.ran, capture.scripts, last, capture.keepIdle, capture.blocks);
8491
9890
  const entries = [];
8492
- for (const [key, { script, functions }] of capture.ran) {
9891
+ for (const [key, { script, functions, executed }] of capture.ran) {
8493
9892
  const entry = { url: script.url, hash: script.hash, functions, pageUrl: script.pageUrl };
9893
+ if (executed) entry.executed = executed;
8494
9894
  const source = await capture.sources.get(key);
8495
9895
  if (source != null) entry.source = source;
8496
9896
  entries.push(entry);
@@ -8507,8 +9907,8 @@ async function stopPageCoverage(page) {
8507
9907
  }
8508
9908
 
8509
9909
  // src/internal/capture/css-coverage.ts
8510
- var crypto4 = __toESM(require("crypto"));
8511
- var fs9 = __toESM(require("fs"));
9910
+ var crypto5 = __toESM(require("crypto"));
9911
+ var fs12 = __toESM(require("fs"));
8512
9912
 
8513
9913
  // ../core/src/css-rules.ts
8514
9914
  var GROUPING = /* @__PURE__ */ new Set(["media", "supports", "layer", "container", "scope", "starting-style", "document"]);
@@ -8648,7 +10048,7 @@ function sourceFile(source, roots) {
8648
10048
  function styleBlockLine(file, index) {
8649
10049
  let text;
8650
10050
  try {
8651
- text = fs9.readFileSync(file, "utf-8");
10051
+ text = fs12.readFileSync(file, "utf-8");
8652
10052
  } catch {
8653
10053
  return 0;
8654
10054
  }
@@ -8676,10 +10076,10 @@ async function sheetMap(sheet, text, fetchMap) {
8676
10076
  return null;
8677
10077
  }
8678
10078
  }
8679
- function sameLines(text, rules, file, lineOffset) {
10079
+ function sameLines2(text, rules, file, lineOffset) {
8680
10080
  let source;
8681
10081
  try {
8682
- source = fs9.readFileSync(file, "utf-8");
10082
+ source = fs12.readFileSync(file, "utf-8");
8683
10083
  } catch {
8684
10084
  return false;
8685
10085
  }
@@ -8714,15 +10114,15 @@ async function resolveSheet(sheet, text, dirs, fetchMap) {
8714
10114
  if (!file2) return null;
8715
10115
  const index = /[?&]index=(\d+)/.exec(sheet.devId);
8716
10116
  const lineOffset2 = /\.(?:vue|svelte|astro)$/i.test(file2) && index ? styleBlockLine(file2, Number(index[1])) : 0;
8717
- return { rules, lookup: null, file: file2, lineOffset: lineOffset2, sources: [], exact: sameLines(text, rules, file2, lineOffset2) };
10117
+ return { rules, lookup: null, file: file2, lineOffset: lineOffset2, sources: [], exact: sameLines2(text, rules, file2, lineOffset2) };
8718
10118
  }
8719
10119
  const file = fileForStyleUrl(sheet.sourceURL, dirs);
8720
10120
  if (!file) return null;
8721
10121
  const lineOffset = sheet.isInline ? sheet.startLine : 0;
8722
- return { rules, lookup: null, file, lineOffset, sources: [], exact: sameLines(text, rules, file, lineOffset) };
10122
+ return { rules, lookup: null, file, lineOffset, sources: [], exact: sameLines2(text, rules, file, lineOffset) };
8723
10123
  }
8724
10124
  function cachedResolution(sheet, text, dirs, fetchMap) {
8725
- const version = crypto4.createHash("sha1").update(text).digest("hex");
10125
+ const version = crypto5.createHash("sha1").update(text).digest("hex");
8726
10126
  const key = [sheet.devId ?? sheet.sourceURL, sheet.isInline ? sheet.startLine : "", dirs.join("\0"), version].join(
8727
10127
  " "
8728
10128
  );
@@ -8769,21 +10169,21 @@ async function resolveCssCoverage(sheets, roots, fetchMap) {
8769
10169
 
8770
10170
  // src/internal/capture/resource-ledger.ts
8771
10171
  var childProcess = __toESM(require("child_process"));
8772
- var fs11 = __toESM(require("fs"));
10172
+ var fs14 = __toESM(require("fs"));
8773
10173
  var net3 = __toESM(require("net"));
8774
- var path14 = __toESM(require("path"));
8775
- var import_node_module2 = require("module");
10174
+ var path17 = __toESM(require("path"));
10175
+ var import_node_module3 = require("module");
8776
10176
 
8777
10177
  // src/internal/capture/worker-metrics.ts
8778
10178
  var import_node_perf_hooks = require("perf_hooks");
8779
10179
 
8780
10180
  // src/internal/support/system-readers.ts
8781
- var fs10 = __toESM(require("fs"));
8782
- var path13 = __toESM(require("path"));
10181
+ var fs13 = __toESM(require("fs"));
10182
+ var path16 = __toESM(require("path"));
8783
10183
  var CLK_TCK = 100;
8784
10184
  function readText(file) {
8785
10185
  try {
8786
- return fs10.readFileSync(file, "utf8");
10186
+ return fs13.readFileSync(file, "utf8");
8787
10187
  } catch {
8788
10188
  return null;
8789
10189
  }
@@ -8822,7 +10222,7 @@ function parsePsiTotal(text) {
8822
10222
  }
8823
10223
  function roleOf(comm, cmdline) {
8824
10224
  const command = `${comm} ${cmdline}`;
8825
- if (/workerProcessEntry/.test(cmdline)) return "worker";
10225
+ if (/workerProcessEntry|[\\/]playwright[\\/]lib[\\/]common[\\/]process\.js/.test(cmdline)) return "worker";
8826
10226
  if (/loaderProcessEntry/.test(cmdline)) return "runner";
8827
10227
  if (/(^|[\s/])ffmpeg/.test(command)) return "ffmpeg";
8828
10228
  const type = /--type=([\w-]+)/.exec(cmdline)?.[1];
@@ -8865,45 +10265,45 @@ var ProcFs = class {
8865
10265
  }
8866
10266
  /** Whether this looks like a Linux `/proc` at all. */
8867
10267
  available() {
8868
- return fs10.existsSync(path13.join(this.root, "stat"));
10268
+ return fs13.existsSync(path16.join(this.root, "stat"));
8869
10269
  }
8870
10270
  /** Every process, keyed by pid. */
8871
10271
  table() {
8872
10272
  const out = /* @__PURE__ */ new Map();
8873
10273
  let names;
8874
10274
  try {
8875
- names = fs10.readdirSync(this.root);
10275
+ names = fs13.readdirSync(this.root);
8876
10276
  } catch {
8877
10277
  return out;
8878
10278
  }
8879
10279
  for (const name of names) {
8880
10280
  if (!/^\d+$/.test(name)) continue;
8881
- const text = readText(path13.join(this.root, name, "stat"));
10281
+ const text = readText(path16.join(this.root, name, "stat"));
8882
10282
  const stat = text ? parseProcStat(Number(name), text) : null;
8883
10283
  if (stat) out.set(stat.pid, stat);
8884
10284
  }
8885
10285
  return out;
8886
10286
  }
8887
10287
  stat(pid) {
8888
- const text = readText(path13.join(this.root, String(pid), "stat"));
10288
+ const text = readText(path16.join(this.root, String(pid), "stat"));
8889
10289
  return text ? parseProcStat(pid, text) : null;
8890
10290
  }
8891
10291
  runWaitMs(pid) {
8892
- const text = readText(path13.join(this.root, String(pid), "schedstat"));
10292
+ const text = readText(path16.join(this.root, String(pid), "schedstat"));
8893
10293
  return text ? parseSchedstat(text) : null;
8894
10294
  }
8895
10295
  cmdline(pid) {
8896
- return (readText(path13.join(this.root, String(pid), "cmdline")) ?? "").split("\0").join(" ").trim();
10296
+ return (readText(path16.join(this.root, String(pid), "cmdline")) ?? "").split("\0").join(" ").trim();
8897
10297
  }
8898
10298
  /** A field of `/proc/<pid>/status`, in kB: `VmRSS`, `VmHWM`. */
8899
10299
  statusKb(pid, key) {
8900
- const text = readText(path13.join(this.root, String(pid), "status"));
10300
+ const text = readText(path16.join(this.root, String(pid), "status"));
8901
10301
  return text ? parseKbField(text, key) : null;
8902
10302
  }
8903
10303
  /** Proportional set size: shared pages split between the processes sharing them, so a sum counts them once. */
8904
10304
  async pssKb(pid) {
8905
10305
  try {
8906
- return parseKbField(await fs10.promises.readFile(path13.join(this.root, String(pid), "smaps_rollup"), "utf8"), "Pss");
10306
+ return parseKbField(await fs13.promises.readFile(path16.join(this.root, String(pid), "smaps_rollup"), "utf8"), "Pss");
8907
10307
  } catch {
8908
10308
  return null;
8909
10309
  }
@@ -8911,29 +10311,29 @@ var ProcFs = class {
8911
10311
  /** Reset a process's peak RSS (`VmHWM`) to its current RSS. */
8912
10312
  resetPeakRss(pid) {
8913
10313
  try {
8914
- fs10.writeFileSync(path13.join(this.root, String(pid), "clear_refs"), "5");
10314
+ fs13.writeFileSync(path16.join(this.root, String(pid), "clear_refs"), "5");
8915
10315
  return true;
8916
10316
  } catch {
8917
10317
  return false;
8918
10318
  }
8919
10319
  }
8920
10320
  cpuTicks() {
8921
- const text = readText(path13.join(this.root, "stat"));
10321
+ const text = readText(path16.join(this.root, "stat"));
8922
10322
  return text ? parseCpuTicks(text) : null;
8923
10323
  }
8924
10324
  /** Total stall time of a resource's pressure file, in µs. */
8925
10325
  pressureUs(resource) {
8926
- const text = readText(path13.join(this.root, "pressure", resource));
10326
+ const text = readText(path16.join(this.root, "pressure", resource));
8927
10327
  return text ? parsePsiTotal(text) : null;
8928
10328
  }
8929
10329
  memAvailableKb() {
8930
- const text = readText(path13.join(this.root, "meminfo"));
10330
+ const text = readText(path16.join(this.root, "meminfo"));
8931
10331
  return text ? parseKbField(text, "MemAvailable") : null;
8932
10332
  }
8933
10333
  /** Open file descriptors of a process. */
8934
10334
  fdCount(pid) {
8935
10335
  try {
8936
- return fs10.readdirSync(path13.join(this.root, String(pid), "fd")).length;
10336
+ return fs13.readdirSync(path16.join(this.root, String(pid), "fd")).length;
8937
10337
  } catch {
8938
10338
  return null;
8939
10339
  }
@@ -9196,11 +10596,21 @@ function runnableOf(info) {
9196
10596
  function fallbackRunnable(window) {
9197
10597
  return { phase: window ? "test" : "worker", fixture: null };
9198
10598
  }
10599
+ var GLOBALS_FILES = [
10600
+ ["lib", "globals.js"],
10601
+ ["lib", "common", "globals.js"]
10602
+ ];
10603
+ function playwrightGlobalsFile() {
10604
+ const packageJson = resolvePlaywrightPackageJson();
10605
+ if (!packageJson) return null;
10606
+ const root = path17.dirname(packageJson);
10607
+ return GLOBALS_FILES.map((parts) => path17.join(root, ...parts)).find((file) => fs14.existsSync(file)) ?? null;
10608
+ }
9199
10609
  function playwrightTestInfoSource() {
9200
10610
  try {
9201
- const packageJson = resolvePlaywrightPackageJson();
9202
- if (!packageJson) return () => null;
9203
- const globals = (0, import_node_module2.createRequire)(packageJson)(path14.join(path14.dirname(packageJson), "lib", "globals.js"));
10611
+ const file = playwrightGlobalsFile();
10612
+ if (!file) return () => null;
10613
+ const globals = (0, import_node_module3.createRequire)(file)(file);
9204
10614
  const read = globals.currentTestInfo;
9205
10615
  if (typeof read !== "function") return () => null;
9206
10616
  return () => {
@@ -9229,7 +10639,7 @@ function countHandles(types = TRACKED_HANDLE_TYPES) {
9229
10639
  async function settledHandles(start, types = TRACKED_HANDLE_TYPES) {
9230
10640
  const end = countHandles(types);
9231
10641
  if (!Object.entries(end).some(([type, n]) => n > (start[type] ?? 0))) return end;
9232
- await new Promise((resolve5) => setTimeout(resolve5, 0));
10642
+ await new Promise((resolve6) => setTimeout(resolve6, 0));
9233
10643
  return countHandles(types);
9234
10644
  }
9235
10645
  function deepUserSite() {
@@ -9243,7 +10653,7 @@ function deepUserSite() {
9243
10653
  }
9244
10654
  var SHELLS = /^(?:sh|bash|dash|zsh|cmd|cmd\.exe|powershell|powershell\.exe|pwsh)$/i;
9245
10655
  function commandOf(spawnfile, spawnargs) {
9246
- const name = (file) => path14.basename(file.replace(/\\/g, "/").replace(/^["']|["']$/g, ""));
10656
+ const name = (file) => path17.basename(file.replace(/\\/g, "/").replace(/^["']|["']$/g, ""));
9247
10657
  const program = typeof spawnfile === "string" ? name(spawnfile) : "";
9248
10658
  const args = Array.isArray(spawnargs) ? spawnargs.map(String) : [];
9249
10659
  const script = args.findIndex((arg) => arg === "-c" || /^\/c$/i.test(arg));
@@ -9257,8 +10667,8 @@ function settleWithin(promise, ms) {
9257
10667
  let timer;
9258
10668
  return Promise.race([
9259
10669
  promise.catch(() => void 0),
9260
- new Promise((resolve5) => {
9261
- timer = setTimeout(resolve5, ms);
10670
+ new Promise((resolve6) => {
10671
+ timer = setTimeout(resolve6, ms);
9262
10672
  })
9263
10673
  ]).finally(() => clearTimeout(timer));
9264
10674
  }
@@ -9378,10 +10788,10 @@ var ResourceLedger = class {
9378
10788
  trackHandle(object, entry) {
9379
10789
  const info = this.testInfoSource();
9380
10790
  const { phase, fixture } = info ? runnableOf(info) : fallbackRunnable(this.window);
9381
- const tracked = { ...entry, phase, fixture, test: testRef2(info) ?? this.window };
9382
- this.handles.add(tracked);
9383
- this.byHandle.set(object, tracked);
9384
- return tracked;
10791
+ const tracked2 = { ...entry, phase, fixture, test: testRef2(info) ?? this.window };
10792
+ this.handles.add(tracked2);
10793
+ this.byHandle.set(object, tracked2);
10794
+ return tracked2;
9385
10795
  }
9386
10796
  onServer(server, site) {
9387
10797
  const known = this.byHandle.get(server);
@@ -9424,7 +10834,7 @@ var ResourceLedger = class {
9424
10834
  const own = () => [...this.handles].filter(
9425
10835
  (entry) => entry.test?.id === testId && !entry.fixture?.worker && (entry.phase === "test" || entry.phase === "beforeEach" || entry.phase === "afterEach")
9426
10836
  );
9427
- if (own().some((entry) => entry.pending?.())) await new Promise((resolve5) => setTimeout(resolve5, 0));
10837
+ if (own().some((entry) => entry.pending?.())) await new Promise((resolve6) => setTimeout(resolve6, 0));
9428
10838
  return own().filter((entry) => entry.running()).map((entry) => ({ type: entry.type, site: entry.site, ...entry.command ? { command: entry.command } : {} }));
9429
10839
  }
9430
10840
  /** Mark a page used: a locator was built on it. */
@@ -9492,7 +10902,7 @@ var ResourceLedger = class {
9492
10902
  const census = this.census(null);
9493
10903
  if (this.resultsFile) {
9494
10904
  try {
9495
- fs11.appendFileSync(this.resultsFile, `${JSON.stringify(census)}
10905
+ appendPrivateFile(this.resultsFile, `${JSON.stringify(census)}
9496
10906
  `);
9497
10907
  } catch {
9498
10908
  }
@@ -10132,9 +11542,18 @@ function createSink() {
10132
11542
  releasedQuietSince: 0,
10133
11543
  releasedUntil: null,
10134
11544
  locatorPages: new LocatorPageLog(),
10135
- codeReach: { sessions: /* @__PURE__ */ new Map(), files: /* @__PURE__ */ new Map(), known: /* @__PURE__ */ new Map(), cssFiles: /* @__PURE__ */ new Map(), cssKnown: /* @__PURE__ */ new Map() },
11545
+ codeReach: {
11546
+ sessions: /* @__PURE__ */ new Map(),
11547
+ files: /* @__PURE__ */ new Map(),
11548
+ known: /* @__PURE__ */ new Map(),
11549
+ lines: /* @__PURE__ */ new Map(),
11550
+ executable: /* @__PURE__ */ new Map(),
11551
+ cssFiles: /* @__PURE__ */ new Map(),
11552
+ cssKnown: /* @__PURE__ */ new Map()
11553
+ },
10136
11554
  serverCoverage: /* @__PURE__ */ new Map(),
10137
- baseURL: null
11555
+ baseURL: null,
11556
+ headless: void 0
10138
11557
  };
10139
11558
  }
10140
11559
  var MAX_CODE_REACH_PAGES = 16;
@@ -10159,7 +11578,7 @@ function maybeStartCodeReach(page, alreadyOpen = false) {
10159
11578
  async function startCodeReachOnOpenPages() {
10160
11579
  if (!pageCoverageInWorker() || OPEN_PAGES.size === 0) return;
10161
11580
  const started = Promise.all([...OPEN_PAGES].map((page) => maybeStartCodeReach(page, true)));
10162
- await Promise.race([started, new Promise((resolve5) => setTimeout(resolve5, CODE_REACH_START_WAIT_MS).unref())]);
11581
+ await Promise.race([started, new Promise((resolve6) => setTimeout(resolve6, CODE_REACH_START_WAIT_MS).unref())]);
10163
11582
  }
10164
11583
  function configuredCodeReachRoots() {
10165
11584
  const raw = process.env.PIWI_CODE_REACH_ROOTS?.trim();
@@ -10173,7 +11592,7 @@ function configuredCodeReachRoots() {
10173
11592
  }
10174
11593
  } catch {
10175
11594
  }
10176
- return raw.split(path15.delimiter).filter(Boolean);
11595
+ return raw.split(path18.delimiter).filter(Boolean);
10177
11596
  }
10178
11597
  async function stopSinkCodeReach(sink, closing) {
10179
11598
  const stopping = [];
@@ -10211,16 +11630,24 @@ async function stopPageCodeReach(sink, page, session, roots) {
10211
11630
  append(sink.codeReach.cssKnown, rules.known);
10212
11631
  }
10213
11632
  if (!scripts) return;
10214
- const { reached, known } = await resolveCodeReachFunctions(scripts, roots, fetchMap, page.url(), {
10215
- known: browserFunctionsInWorker()
10216
- });
11633
+ const { reached, known, lines, executable } = await resolveCodeReachFunctions(
11634
+ scripts,
11635
+ roots,
11636
+ fetchMap,
11637
+ page.url(),
11638
+ { known: browserFunctionsInWorker(), lines: browserLinesInWorker() }
11639
+ );
10217
11640
  append(sink.codeReach.files, reached);
10218
11641
  append(sink.codeReach.known, known);
11642
+ append(sink.codeReach.lines, lines);
11643
+ append(sink.codeReach.executable, executable);
10219
11644
  } catch {
10220
11645
  }
10221
11646
  }
10222
11647
  var currentSink = null;
10223
11648
  var KNOWN_FUNCTIONS_SENT = /* @__PURE__ */ new Map();
11649
+ var EXECUTABLE_LINES_SENT = /* @__PURE__ */ new Map();
11650
+ var RAN_LINES_SENT = /* @__PURE__ */ new Map();
10224
11651
  var KNOWN_CSS_RULES_SENT = /* @__PURE__ */ new Map();
10225
11652
  var PENDING_PROBES = /* @__PURE__ */ new Set();
10226
11653
  async function drainPendingProbes(capMs) {
@@ -10228,8 +11655,8 @@ async function drainPendingProbes(capMs) {
10228
11655
  let cap;
10229
11656
  await Promise.race([
10230
11657
  Promise.allSettled(PENDING_PROBES),
10231
- new Promise((resolve5) => {
10232
- cap = setTimeout(resolve5, capMs);
11658
+ new Promise((resolve6) => {
11659
+ cap = setTimeout(resolve6, capMs);
10233
11660
  })
10234
11661
  ]);
10235
11662
  clearTimeout(cap);
@@ -10288,10 +11715,10 @@ async function readWebVitals(page) {
10288
11715
  const key = entry.name.replace(/-([a-z])/g, (_, l) => l.toUpperCase());
10289
11716
  paint[key] = Math.round(entry.startTime);
10290
11717
  }
10291
- const readBuffered = (type, extra) => new Promise((resolve5) => {
11718
+ const readBuffered = (type, extra) => new Promise((resolve6) => {
10292
11719
  try {
10293
11720
  const PO = globalThis.PerformanceObserver;
10294
- if (!PO || !(PO.supportedEntryTypes || []).includes(type)) return resolve5(null);
11721
+ if (!PO || !(PO.supportedEntryTypes || []).includes(type)) return resolve6(null);
10295
11722
  const out = [];
10296
11723
  const po = new PO((list) => out.push(...list.getEntries()));
10297
11724
  po.observe({ type, buffered: true, ...extra });
@@ -10301,10 +11728,10 @@ async function readWebVitals(page) {
10301
11728
  po.disconnect();
10302
11729
  } catch {
10303
11730
  }
10304
- resolve5(out);
11731
+ resolve6(out);
10305
11732
  }, 0);
10306
11733
  } catch {
10307
- resolve5(null);
11734
+ resolve6(null);
10308
11735
  }
10309
11736
  });
10310
11737
  const [lcpRaw, shiftRaw, eventRaw, firstInputRaw] = await Promise.all([
@@ -10421,12 +11848,12 @@ var PAGE_INVENTORY_IN_PAGE_CAP = 2e3;
10421
11848
  var PAGE_INVENTORY_EVAL_TIMEOUT_MS = 2e3;
10422
11849
  var MAX_PAGE_INVENTORY_WINDOWS = 64;
10423
11850
  function withTimeout(promise, ms) {
10424
- return new Promise((resolve5, reject) => {
11851
+ return new Promise((resolve6, reject) => {
10425
11852
  const timer = setTimeout(() => reject(new Error("page inventory read timed out")), ms);
10426
11853
  promise.then(
10427
11854
  (value) => {
10428
11855
  clearTimeout(timer);
10429
- resolve5(value);
11856
+ resolve6(value);
10430
11857
  },
10431
11858
  (error) => {
10432
11859
  clearTimeout(timer);
@@ -10545,6 +11972,20 @@ var PATCHED_BROWSERS = /* @__PURE__ */ new WeakSet();
10545
11972
  var CHAIN_METHOD_SET = new Set(CHAIN_METHODS);
10546
11973
  var ACTION_METHOD_SET = new Set(ACTION_METHODS);
10547
11974
  var LOCATOR_METHOD_SET = new Set(LOCATOR_METHODS);
11975
+ var EARLY_READ_ACTIONS = /* @__PURE__ */ new Set([
11976
+ "click",
11977
+ "dblclick",
11978
+ "tap",
11979
+ "press",
11980
+ "pressSequentially",
11981
+ "type",
11982
+ "check",
11983
+ "uncheck",
11984
+ "selectOption",
11985
+ "dispatchEvent"
11986
+ ]);
11987
+ var CAPTURE_DEADLINE_MS = 500;
11988
+ var EARLY_READ_TRUSTED_MS = 250;
10548
11989
  var CAPTURED_ATTRS_ARG = {
10549
11990
  keep: [...CAPTURED_ATTRIBUTES],
10550
11991
  tagRoles: TAG_TO_ROLE,
@@ -10563,15 +12004,36 @@ var PROBE_INIT_SCRIPT = `(() => {
10563
12004
  globalThis[${JSON.stringify(PROBE_GLOBAL)}] = (el) => probe(el, arg);
10564
12005
  })();`;
10565
12006
  var PROBE_UNSEEDED_PAGES = /* @__PURE__ */ new WeakSet();
10566
- function probeElement(page, target) {
10567
- const shipSource = () => target.evaluate(probeElementAttrs, CAPTURED_ATTRS_ARG);
12007
+ var PAGE_NAVIGATIONS = /* @__PURE__ */ new WeakMap();
12008
+ function readyProbeWorld(page) {
12009
+ if (!currentSink) return;
12010
+ try {
12011
+ const ready = internalCall(
12012
+ page,
12013
+ () => page.mainFrame().locator(":root").evaluate(() => 0, void 0, { timeout: CAPTURE_DEADLINE_MS })
12014
+ ).then(
12015
+ () => void 0,
12016
+ () => void 0
12017
+ );
12018
+ PENDING_PROBES.add(ready);
12019
+ void ready.then(() => PENDING_PROBES.delete(ready));
12020
+ } catch {
12021
+ }
12022
+ }
12023
+ function probeElement(page, target, timeout) {
12024
+ const options = timeout != null ? { timeout } : void 0;
12025
+ const shipSource = () => target.evaluate(probeElementAttrs, CAPTURED_ATTRS_ARG, options);
10568
12026
  if (!page || PROBE_UNSEEDED_PAGES.has(page)) return internalCall(page, shipSource);
10569
12027
  return internalCall(
10570
12028
  page,
10571
- () => target.evaluate((el, name) => {
10572
- const seeded = globalThis[name];
10573
- return typeof seeded === "function" ? seeded(el) : null;
10574
- }, PROBE_GLOBAL).then((attrs) => {
12029
+ () => target.evaluate(
12030
+ (el, name) => {
12031
+ const seeded = globalThis[name];
12032
+ return typeof seeded === "function" ? seeded(el) : null;
12033
+ },
12034
+ PROBE_GLOBAL,
12035
+ options
12036
+ ).then((attrs) => {
10575
12037
  if (attrs) return attrs;
10576
12038
  PROBE_UNSEEDED_PAGES.add(page);
10577
12039
  return shipSource();
@@ -10606,54 +12068,60 @@ async function ariaSnapshotJSONBestEffort(target, timeout) {
10606
12068
  return null;
10607
12069
  }
10608
12070
  }
10609
- function startElementCapture(sink, page, target, seq, callerLocation, used) {
10610
- const probe = probeElement(page, target);
10611
- const settledProbe = probe.then(
10612
- () => void 0,
10613
- () => void 0
10614
- );
10615
- PENDING_PROBES.add(settledProbe);
10616
- settledProbe.then(() => PENDING_PROBES.delete(settledProbe));
10617
- sink.capturePromises.push(settledProbe);
10618
- const resolveAttrs = (async () => {
10619
- let deadline;
10620
- try {
10621
- const attrs = await Promise.race([
10622
- probe,
10623
- new Promise((_, reject) => {
10624
- deadline = setTimeout(() => reject(new Error("locator capture timeout")), 500);
10625
- })
10626
- ]);
10627
- const role = resolveAriaRole({ ...attrs, accessibleName: null });
10628
- const isFormField = FORM_FIELD_TAGS.has(attrs.tagName);
10629
- const exactName = exactAccessibleName(attrs, role);
10630
- const aria = exactName === null && (role || isFormField) ? await internalCall(page, () => ariaSnapshotBestEffort(target, 500)) : null;
10631
- const accessibleName = exactName ?? (extractAccessibleName(aria) || approximateAccessibleName({ ...attrs, accessibleName: null }));
10632
- sink.capturedLocators[seq] = {
10633
- location: callerLocation,
10634
- used,
10635
- // hasLabel/selectorCounts inform alternative generation only —
10636
- // keep the stored element to the wire shape. rolePosition and
10637
- // ancestors ARE wire fields: the server's renamed-element match
10638
- // uses them at heal time.
10639
- element: {
10640
- tagName: attrs.tagName,
10641
- attributes: attrs.attributes,
10642
- textContent: attrs.textContent,
10643
- accessibleName,
10644
- center: attrs.center,
10645
- ...attrs.rolePosition ? { rolePosition: attrs.rolePosition } : {},
10646
- ...attrs.ancestors && attrs.ancestors.length > 0 ? { ancestors: attrs.ancestors } : {}
10647
- },
10648
- alternatives: generateAlternatives({ ...attrs, accessibleName })
10649
- };
10650
- } catch {
10651
- if (callerLocation) sink.probedLocations.delete(callerLocation);
10652
- } finally {
10653
- clearTimeout(deadline);
10654
- }
12071
+ async function readElementSnapshot(sink, page, target, callerLocation, used) {
12072
+ let deadline;
12073
+ try {
12074
+ const probe = probeElement(page, target, CAPTURE_DEADLINE_MS);
12075
+ const settledProbe = probe.then(
12076
+ () => void 0,
12077
+ () => void 0
12078
+ );
12079
+ PENDING_PROBES.add(settledProbe);
12080
+ settledProbe.then(() => PENDING_PROBES.delete(settledProbe));
12081
+ sink.capturePromises.push(settledProbe);
12082
+ const attrs = await Promise.race([
12083
+ probe,
12084
+ new Promise((_, reject) => {
12085
+ deadline = setTimeout(() => reject(new Error("locator capture timeout")), CAPTURE_DEADLINE_MS);
12086
+ })
12087
+ ]);
12088
+ const role = resolveAriaRole({ ...attrs, accessibleName: null });
12089
+ const isFormField = FORM_FIELD_TAGS.has(attrs.tagName);
12090
+ const exactName = exactAccessibleName(attrs, role);
12091
+ const aria = exactName === null && (role || isFormField) ? await internalCall(page, () => ariaSnapshotBestEffort(target, CAPTURE_DEADLINE_MS)) : null;
12092
+ const accessibleName = exactName ?? (extractAccessibleName(aria) || approximateAccessibleName({ ...attrs, accessibleName: null }));
12093
+ return {
12094
+ location: callerLocation,
12095
+ used,
12096
+ // hasLabel/selectorCounts inform alternative generation only —
12097
+ // keep the stored element to the wire shape. rolePosition and
12098
+ // ancestors ARE wire fields: the server's renamed-element match
12099
+ // uses them at heal time.
12100
+ element: {
12101
+ tagName: attrs.tagName,
12102
+ attributes: attrs.attributes,
12103
+ textContent: attrs.textContent,
12104
+ accessibleName,
12105
+ center: attrs.center,
12106
+ ...attrs.rolePosition ? { rolePosition: attrs.rolePosition } : {},
12107
+ ...attrs.ancestors && attrs.ancestors.length > 0 ? { ancestors: attrs.ancestors } : {}
12108
+ },
12109
+ alternatives: generateAlternatives({ ...attrs, accessibleName })
12110
+ };
12111
+ } catch {
12112
+ return null;
12113
+ } finally {
12114
+ clearTimeout(deadline);
12115
+ }
12116
+ }
12117
+ function startElementCapture(sink, page, target, seq, callerLocation, used, early = null, earlyFirst = false) {
12118
+ const capture = (async () => {
12119
+ const readNow = () => readElementSnapshot(sink, page, target, callerLocation, used);
12120
+ const snapshot = earlyFirst ? await early ?? await readNow() : await readNow() ?? await early;
12121
+ if (snapshot) sink.capturedLocators[seq] = snapshot;
12122
+ else if (callerLocation) sink.probedLocations.delete(callerLocation);
10655
12123
  })();
10656
- sink.capturePromises.push(resolveAttrs);
12124
+ sink.capturePromises.push(capture);
10657
12125
  }
10658
12126
  function recordLocatorPage(sink, page, locator, location, arrival) {
10659
12127
  try {
@@ -10665,7 +12133,7 @@ function knowLocatorCall(sink, page, target, location, origin) {
10665
12133
  if (!sink?.pause || !location) return null;
10666
12134
  let settle = () => {
10667
12135
  };
10668
- const settled = new Promise((resolve5) => settle = resolve5);
12136
+ const settled = new Promise((resolve6) => settle = resolve6);
10669
12137
  const call = { page, target, location, origin, picked: false, endable: false, settled, settle };
10670
12138
  sink.locatorCalls.set(callSiteLine(location), call);
10671
12139
  return call;
@@ -10773,7 +12241,7 @@ function endedWaiting(sink, call) {
10773
12241
  return "finish";
10774
12242
  }
10775
12243
  function stopSite(sink, location) {
10776
- if (path15.dirname(path15.resolve(location.file)) !== __dirname) return stopCallSite(location);
12244
+ if (path18.dirname(path18.resolve(location.file)) !== __dirname) return stopCallSite(location);
10777
12245
  return inFlightCallSite([...sink.locatorCalls.values()].map((call) => call.location));
10778
12246
  }
10779
12247
  function stopBarPage(sink, context, of) {
@@ -10788,7 +12256,7 @@ async function showStop(sink, context, title, location, reason, call, of, failur
10788
12256
  const page = stopBarPage(sink, context, of);
10789
12257
  const guessed = !("page" in of);
10790
12258
  if (!testInfo) return void 0;
10791
- const bar = !!page && testInfo.project?.use?.headless === false;
12259
+ const bar = !!page && pauseGateFromTestInfo(testInfo, sink.headless).headless === false;
10792
12260
  const place = runChannelOpen() ? callSitePlace(location) : null;
10793
12261
  if (!bar && !place) return void 0;
10794
12262
  const failing = failure?.failed ?? null;
@@ -10896,6 +12364,7 @@ async function showStop(sink, context, title, location, reason, call, of, failur
10896
12364
  }
10897
12365
  return "resume";
10898
12366
  }
12367
+ const stoppedOn = call?.page === page ? call : null;
10899
12368
  return internalCall(
10900
12369
  page,
10901
12370
  () => pauseHere(
@@ -10904,7 +12373,14 @@ async function showStop(sink, context, title, location, reason, call, of, failur
10904
12373
  location,
10905
12374
  call: title,
10906
12375
  attempt: testInfo.retry > 0 ? testInfo.retry + 1 : null,
10907
- target: call?.page === page ? call.target : null,
12376
+ target: stoppedOn ? {
12377
+ highlight: () => highlightAtStop(
12378
+ page,
12379
+ stoppedOn.target,
12380
+ "call",
12381
+ locatorSource(stoppedOn.target, stoppedOn.origin.method, stoppedOn.origin.args)
12382
+ )
12383
+ } : null,
10908
12384
  ...failure ? { failure: true } : sink.functionEnded ? {} : { end: true }
10909
12385
  },
10910
12386
  probe,
@@ -10951,7 +12427,7 @@ function endTest(sink, call, title, location, reason) {
10951
12427
  return "end";
10952
12428
  }
10953
12429
  const said = hideSecretsInText(
10954
- `${title} at ${line} runs before the test ends: Piwi holds no locator call there. The test is skipped at its next locator call, or as it ends.`
12430
+ call && !takesEndSignal(sink.testInfo.config?.version) ? `${title} at ${line} runs before the test ends: a locator call is given up from Playwright 1.62 on. The test is skipped as the call returns.` : `${title} at ${line} runs before the test ends: Piwi holds no locator call there. The test is skipped at its next locator call, or as it ends.`
10955
12431
  );
10956
12432
  console.log(`[piwi] ${said}`);
10957
12433
  tellHub({ type: "notice", message: said });
@@ -11110,8 +12586,8 @@ function errorPlace(error, windows = process.platform === "win32") {
11110
12586
  for (const line of typeof stack === "string" ? stack.split("\n") : []) {
11111
12587
  const frame = /^\s*at\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?$/.exec(line);
11112
12588
  const file = frame ? framePath(frame[1], windows) : null;
11113
- if (!frame || !file || !(windows ? path15.win32 : path15.posix).isAbsolute(file)) continue;
11114
- if (/[\\/]node_modules[\\/]/.test(file) || path15.dirname(path15.resolve(file)) === __dirname) continue;
12589
+ if (!frame || !file || !(windows ? path18.win32 : path18.posix).isAbsolute(file)) continue;
12590
+ if (/[\\/]node_modules[\\/]/.test(file) || path18.dirname(path18.resolve(file)) === __dirname) continue;
11115
12591
  return { file, line: Number(frame[2]), column: Number(frame[3]) };
11116
12592
  }
11117
12593
  return null;
@@ -11122,7 +12598,7 @@ function callInProgress(testInfo) {
11122
12598
  if (!Array.isArray(steps)) return;
11123
12599
  for (const step of steps) {
11124
12600
  if (step.endWallTime) continue;
11125
- const at = step.stack?.[0];
12601
+ const at = step.stack?.[0] ?? step.location;
11126
12602
  const called = step.category === "pw:api" || step.category === "expect" || step.category === "test.step";
11127
12603
  if (called && typeof at?.file === "string" && typeof at.line === "number") {
11128
12604
  found = {
@@ -11142,13 +12618,13 @@ function stepInProgress(testInfo) {
11142
12618
  function runningCall(testInfo) {
11143
12619
  const call = callInProgress(testInfo);
11144
12620
  if (!call?.title) return null;
11145
- const file = path15.relative(process.cwd(), call.place.file).split(path15.sep).join("/");
12621
+ const file = path18.relative(process.cwd(), call.place.file).split(path18.sep).join("/");
11146
12622
  return { title: call.title, file, line: call.place.line };
11147
12623
  }
11148
12624
  function abortion(signal) {
11149
- return new Promise((resolve5) => {
11150
- if (signal.aborted) resolve5();
11151
- else signal.addEventListener("abort", () => resolve5(), { once: true });
12625
+ return new Promise((resolve6) => {
12626
+ if (signal.aborted) resolve6();
12627
+ else signal.addEventListener("abort", () => resolve6(), { once: true });
11152
12628
  });
11153
12629
  }
11154
12630
  var END_STOP_MS = 2e3;
@@ -11183,7 +12659,7 @@ function releaseCall(sink, settled) {
11183
12659
  }
11184
12660
  function releasedRequestsEnded(sink) {
11185
12661
  if (sink.releasedRequests.size === 0) return Promise.resolve();
11186
- return new Promise((resolve5) => sink.onReleasedRequestsEnded = resolve5);
12662
+ return new Promise((resolve6) => sink.onReleasedRequestsEnded = resolve6);
11187
12663
  }
11188
12664
  async function awaitReleasedCalls(sink) {
11189
12665
  if (sink.released.length === 0) return;
@@ -11196,13 +12672,13 @@ async function awaitReleasedCalls(sink) {
11196
12672
  }
11197
12673
  const quiet = now - sink.releasedQuietSince;
11198
12674
  if (quiet >= RELEASED_QUIET_MS) return;
11199
- await new Promise((resolve5) => setTimeout(resolve5, Math.min(RELEASED_QUIET_MS - quiet, deadline - now)));
12675
+ await new Promise((resolve6) => setTimeout(resolve6, Math.min(RELEASED_QUIET_MS - quiet, deadline - now)));
11200
12676
  }
11201
12677
  }
11202
12678
  async function settledWithin(pending, ms) {
11203
12679
  if (pending.length === 0) return;
11204
12680
  let timer;
11205
- await Promise.race([Promise.allSettled(pending), new Promise((resolve5) => timer = setTimeout(resolve5, ms))]);
12681
+ await Promise.race([Promise.allSettled(pending), new Promise((resolve6) => timer = setTimeout(resolve6, ms))]);
11206
12682
  clearTimeout(timer);
11207
12683
  }
11208
12684
  function endStopsWithTestFunction(testInfo, sink) {
@@ -11235,7 +12711,7 @@ async function pauseInPlace(page, playwrightPause, location) {
11235
12711
  if (!sink || !testInfo || !location || !context || !contextDebugger(context)) {
11236
12712
  return leaveToPlaywright(context, playwrightPause);
11237
12713
  }
11238
- if (!sink.pause && (!canRecordFromHere() || pauseSkipReason(pauseGateFromTestInfo(testInfo)))) {
12714
+ if (!sink.pause && (!canRecordFromHere() || pauseSkipReason(pauseGateFromTestInfo(testInfo, sink.headless)))) {
11239
12715
  return leaveToPlaywright(context, playwrightPause);
11240
12716
  }
11241
12717
  sink.pause ??= pauseState(NO_BREAKPOINTS);
@@ -11303,7 +12779,7 @@ function wrapLocator(page, locator, originMethod, originArgs) {
11303
12779
  const callerLocation = sink ? captureCallerLocation() : null;
11304
12780
  if (sink) recordLocatorPage(sink, page, target, callerLocation, noteLocatorCall(page, EXPECT_METHOD, true));
11305
12781
  const call = knowLocatorCall(sink, page, target, callerLocation, { method: originMethod, args: originArgs });
11306
- const ending = sink?.pause && !sink.ended ? withEndSignal(EXPECT_METHOD, callArgs, sink.end.signal) : null;
12782
+ const ending = sink?.pause && !sink.ended && takesEndSignal(sink.testInfo?.config?.version) ? withEndSignal(EXPECT_METHOD, callArgs, sink.end.signal) : null;
11307
12783
  if (call && ending) call.endable = true;
11308
12784
  const expectArgs = ending ?? callArgs;
11309
12785
  try {
@@ -11356,7 +12832,7 @@ function wrapLocator(page, locator, originMethod, originArgs) {
11356
12832
  raw: `${originMethod}(${JSON.stringify(originArgs)})`
11357
12833
  };
11358
12834
  const call = knowLocatorCall(sink, page, target, callerLocation, used);
11359
- const ending = sink.pause && !sink.ended ? withEndSignal(String(prop), callArgs, sink.end.signal) : null;
12835
+ const ending = sink.pause && !sink.ended && takesEndSignal(sink.testInfo?.config?.version) ? withEndSignal(String(prop), callArgs, sink.end.signal) : null;
11360
12836
  if (call && ending) call.endable = true;
11361
12837
  const alreadyProbed = callerLocation !== null && sink.probedLocations.has(callerLocation);
11362
12838
  let seq = -1;
@@ -11369,7 +12845,10 @@ function wrapLocator(page, locator, originMethod, originArgs) {
11369
12845
  alternatives: []
11370
12846
  });
11371
12847
  }
12848
+ const early = !alreadyProbed && EARLY_READ_ACTIONS.has(prop) ? readElementSnapshot(sink, page, target, callerLocation, used) : null;
11372
12849
  let result;
12850
+ const startedAt = Date.now();
12851
+ const navigations = PAGE_NAVIGATIONS.get(page) ?? 0;
11373
12852
  try {
11374
12853
  result = await callMethod(target, prop, ending ?? callArgs);
11375
12854
  } catch (error) {
@@ -11382,7 +12861,8 @@ function wrapLocator(page, locator, originMethod, originArgs) {
11382
12861
  if (endsNow(sink)) throw skipOf(sink);
11383
12862
  if (!alreadyProbed && !call?.picked) {
11384
12863
  if (callerLocation) sink.probedLocations.add(callerLocation);
11385
- startElementCapture(sink, page, target, seq, callerLocation, used);
12864
+ const earlyFirst = (PAGE_NAVIGATIONS.get(page) ?? 0) !== navigations || Date.now() - startedAt < EARLY_READ_TRUSTED_MS;
12865
+ startElementCapture(sink, page, target, seq, callerLocation, used, early, earlyFirst);
11386
12866
  }
11387
12867
  return result;
11388
12868
  };
@@ -11444,7 +12924,7 @@ function instrumentPage(page) {
11444
12924
  page.close = async (...args) => {
11445
12925
  let closed = () => {
11446
12926
  };
11447
- CLOSING_PAGES.set(page, new Promise((resolve5) => closed = resolve5));
12927
+ CLOSING_PAGES.set(page, new Promise((resolve6) => closed = resolve6));
11448
12928
  try {
11449
12929
  await settleBeforeClose({ page });
11450
12930
  return await originalClose(...args);
@@ -11472,10 +12952,14 @@ function instrumentPage(page) {
11472
12952
  };
11473
12953
  }
11474
12954
  if (typeof page.on === "function") {
12955
+ page.on("domcontentloaded", () => readyProbeWorld(page));
11475
12956
  page.on("framenavigated", (frame) => {
11476
12957
  PROBE_UNSEEDED_PAGES.delete(page);
11477
12958
  try {
11478
- if (frame === page.mainFrame()) noteNavigation(page);
12959
+ if (frame === page.mainFrame()) {
12960
+ PAGE_NAVIGATIONS.set(page, (PAGE_NAVIGATIONS.get(page) ?? 0) + 1);
12961
+ noteNavigation(page);
12962
+ }
11479
12963
  } catch {
11480
12964
  }
11481
12965
  });
@@ -11756,8 +13240,8 @@ async function flushSink(sink, testInfo) {
11756
13240
  let drainDeadline;
11757
13241
  await Promise.race([
11758
13242
  Promise.allSettled(sink.capturePromises),
11759
- new Promise((resolve5) => {
11760
- drainDeadline = setTimeout(resolve5, 2e3);
13243
+ new Promise((resolve6) => {
13244
+ drainDeadline = setTimeout(resolve6, 2e3);
11761
13245
  })
11762
13246
  ]);
11763
13247
  clearTimeout(drainDeadline);
@@ -11789,7 +13273,7 @@ async function flushSink(sink, testInfo) {
11789
13273
  contentType: "application/json",
11790
13274
  body: Buffer.from(JSON.stringify(finalizeCodeReach(sink.codeReach.files.keys())))
11791
13275
  });
11792
- const functions = browserFunctionsInWorker() ? browserFunctionCoverage(sink.codeReach.files) : null;
13276
+ const functions = browserFunctionsInWorker() ? browserFunctionCoverage(sink.codeReach.files, browserLinesInWorker() ? sink.codeReach.lines : void 0) : null;
11793
13277
  if (functions) {
11794
13278
  await testInfo.attach(ATTACHMENT_NAMES.browserCoverage, {
11795
13279
  contentType: "application/json",
@@ -11804,6 +13288,13 @@ async function flushSink(sink, testInfo) {
11804
13288
  body: Buffer.from(JSON.stringify(part))
11805
13289
  });
11806
13290
  }
13291
+ const fileLines = browserLinesInWorker() ? newBrowserLines(sink.codeReach.executable, sink.codeReach.lines, EXECUTABLE_LINES_SENT, RAN_LINES_SENT) : [];
13292
+ for (const part of fileLines) {
13293
+ await testInfo.attach(ATTACHMENT_NAMES.browserLines, {
13294
+ contentType: "application/json",
13295
+ body: Buffer.from(JSON.stringify(part))
13296
+ });
13297
+ }
11807
13298
  if (cssCoverageInWorker()) {
11808
13299
  const rules = sink.codeReach.cssFiles.size > 0 ? browserFunctionCoverage(sink.codeReach.cssFiles) : null;
11809
13300
  if (rules) {
@@ -11964,7 +13455,7 @@ var runControl = {
11964
13455
  return;
11965
13456
  }
11966
13457
  if (!sink.pause) {
11967
- const why = sink.testInfo ? pauseSkipReason({ ...pauseGateFromTestInfo(sink.testInfo), channel: true }) : null;
13458
+ const why = sink.testInfo ? pauseSkipReason({ ...pauseGateFromTestInfo(sink.testInfo, sink.headless), channel: true }) : null;
11968
13459
  tellHub({ type: "notice", message: `This test does not stop${why ? `: ${why}` : ""}.` });
11969
13460
  return;
11970
13461
  }
@@ -11986,7 +13477,7 @@ var runControl = {
11986
13477
  }
11987
13478
  };
11988
13479
  function runFile(file) {
11989
- return path15.relative(process.cwd(), file).split(path15.sep).join("/") || file;
13480
+ return path18.relative(process.cwd(), file).split(path18.sep).join("/") || file;
11990
13481
  }
11991
13482
  function testBegin(testInfo, cannotPause) {
11992
13483
  const title = testInfo.titlePath.slice(1);
@@ -12026,6 +13517,7 @@ var piwiFixtures = {
12026
13517
  startResourceLedger(playwright, workerInfo.workerIndex);
12027
13518
  observeApiRequests(playwright, apiCallRecorder);
12028
13519
  openLiveView(workerInfo);
13520
+ if (liveViewOpen()) trackCalls(playwright);
12029
13521
  if (await openRunChannel(workerInfo, runControl)) watchCalls(playwright);
12030
13522
  try {
12031
13523
  await use();
@@ -12063,17 +13555,18 @@ var piwiFixtures = {
12063
13555
  // (attach the collected data) at teardown. Runs for every test without being
12064
13556
  // requested, so suites that never destructure `page` are still captured.
12065
13557
  piwiCapture: [
12066
- async ({ screenshot, baseURL }, use, testInfo) => {
13558
+ async ({ screenshot, baseURL, headless }, use, testInfo) => {
12067
13559
  boxCaptureFrames();
12068
13560
  const conflict = labModeConflict();
12069
13561
  if (conflict) throw new Error(conflict);
12070
13562
  const sink = createSink();
12071
13563
  sink.testInfo = testInfo;
12072
13564
  sink.baseURL = baseURL ?? null;
13565
+ sink.headless = headless;
12073
13566
  if (keepsFailureScreenshots(screenshot, testInfo.retry)) sink.failureScreenshot = screenshot;
12074
13567
  const pauseSet = currentPauseSet();
12075
13568
  const channel = runChannelOpen();
12076
- const cannotPause = pauseSkipReason({ ...pauseGateFromTestInfo(testInfo), channel });
13569
+ const cannotPause = pauseSkipReason({ ...pauseGateFromTestInfo(testInfo, headless), channel });
12077
13570
  if (pauseSet.size || channel) {
12078
13571
  if (!cannotPause) sink.pause = pauseState(pauseSet, pauseNextTest);
12079
13572
  else if (pauseSet.size) logPauseSkipOnce(cannotPause);
@@ -12105,7 +13598,7 @@ var piwiFixtures = {
12105
13598
  });
12106
13599
  activeResourceLedger()?.testStarted(testInfo);
12107
13600
  currentSink = sink;
12108
- liveViewTestBegan(testInfo.title, () => runningCall(testInfo));
13601
+ liveViewTestBegan(testInfo.title, () => runningCall(testInfo), mayPause(pauseGateFromTestInfo(testInfo)));
12109
13602
  const showRunChannel = hideRunChannel();
12110
13603
  try {
12111
13604
  await armStops(OPEN_CONTEXTS);
@@ -12123,9 +13616,10 @@ var piwiFixtures = {
12123
13616
  const applied = sink.probeInterception?.applied() ?? false;
12124
13617
  const level = sink.probeItem.level ?? "client";
12125
13618
  const handled = level === "server" && applied ? classifyProbeHandled({
12126
- consoleErrors: sink.consoleEntries.filter((e) => e.type === "error").length,
13619
+ consoleErrors: probeConsoleErrors(sink.consoleEntries),
12127
13620
  dialogs: sink.dialogs.length,
12128
13621
  backendError: sink.probeInterception?.serverError() ?? false,
13622
+ faultIsTheError: faultIsTheError(sink.probeItem.fault),
12129
13623
  pageErrors: sink.probePageErrors,
12130
13624
  blankPage: sink.probeBlankPage
12131
13625
  }) : "n/a";