tagreeve 0.7.0 → 0.8.0-rc.2

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.
Files changed (4) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +10 -4
  3. package/dist/cli.js +1154 -196
  4. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -508,14 +508,17 @@ function* keyedDigests(text2) {
508
508
  }
509
509
  }
510
510
  }
511
- function* variants(text2, depth = 0, seen = /* @__PURE__ */ new Set()) {
511
+ function* readingsOf(text2, fromBase64 = false, depth = 0, seen = /* @__PURE__ */ new Set()) {
512
512
  if (seen.has(text2)) return;
513
513
  seen.add(text2);
514
- yield text2;
514
+ yield { text: text2, fromBase64 };
515
515
  const url = tryUrlDecode(text2);
516
- if (url !== void 0 && url !== text2) yield* variants(url, depth, seen);
516
+ if (url !== void 0 && url !== text2) yield* readingsOf(url, fromBase64, depth, seen);
517
517
  if (depth >= MAX_DEPTH) return;
518
- for (const decoded of base64Decodes(text2)) yield* variants(decoded, depth + 1, seen);
518
+ for (const decoded of base64Decodes(text2)) yield* readingsOf(decoded, true, depth + 1, seen);
519
+ }
520
+ function* variants(text2) {
521
+ for (const reading of readingsOf(text2)) yield reading.text;
519
522
  }
520
523
  function readings(text2) {
521
524
  return [...variants(text2)];
@@ -557,24 +560,24 @@ function ownValues(identity) {
557
560
  const extraPhones = extra.map((v) => v.replace(/\D/g, "")).filter((v) => v.length >= 8);
558
561
  return { email, phoneDigits, nationalDigits: format.nationalDigits(phoneDigits), hashes, extraEmails, extraPhones };
559
562
  }
560
- function* candidates(text2) {
561
- for (const variant of variants(text2)) {
563
+ function* candidates(text2, literal = false) {
564
+ for (const { text: variant, fromBase64 } of readingsOf(text2)) {
562
565
  if (!hasUrlEscapes(variant)) {
563
566
  for (const raw of variant.match(EMAIL) ?? []) {
564
- const m = raw.slice(raw.lastIndexOf("+") + 1);
567
+ const m = literal ? raw : raw.slice(raw.lastIndexOf("+") + 1);
565
568
  if (!m.includes("@") || FILE_EXTENSION.test(m)) continue;
566
- const both = raw !== m && raw.indexOf("+") === raw.lastIndexOf("+") && !raw.startsWith("+");
567
- yield { kind: "email", value: m, alternate: both ? raw : void 0, variant, index: 0 };
569
+ const both = !literal && raw !== m && raw.indexOf("+") === raw.lastIndexOf("+") && !raw.startsWith("+");
570
+ yield { kind: "email", value: m, alternate: both ? raw : void 0, variant, index: 0, fromBase64 };
568
571
  }
569
572
  }
570
573
  for (const m of variant.match(PHONE) ?? []) {
571
574
  const digits2 = m.replace(/\D/g, "");
572
575
  if (digits2.length < 8 || digits2.length > 15) continue;
573
576
  if (/^\+\d+\+/.test(m) && !/^\+\d{1,3}\+/.test(m)) continue;
574
- yield { kind: "phone", value: m, variant, index: 0 };
577
+ yield { kind: "phone", value: m, variant, index: 0, fromBase64 };
575
578
  }
576
579
  if (!hasUrlEscapes(variant)) {
577
- for (const m of variant.matchAll(HASH)) yield { kind: "hash", value: m[0].toLowerCase(), variant, index: m.index };
580
+ for (const m of variant.matchAll(HASH)) yield { kind: "hash", value: m[0].toLowerCase(), variant, index: m.index, fromBase64 };
578
581
  }
579
582
  }
580
583
  }
@@ -583,39 +586,47 @@ function valueKinds(text2) {
583
586
  for (const c of candidates(text2)) kinds.add(c.kind);
584
587
  return kinds;
585
588
  }
586
- function ownValueKinds(text2, identity) {
589
+ function isOwnEmail(value, own, fromBase64) {
590
+ const email = normalizeEmail(value);
591
+ return own.extraEmails.includes(email) || (fromBase64 ? email.includes(own.email) : email === own.email);
592
+ }
593
+ function isOwnPhone(digits2, own, fromBase64) {
594
+ if (own.extraPhones.includes(digits2)) return true;
595
+ return fromBase64 ? digits2.includes(own.phoneDigits) || digits2.includes(own.nationalDigits) : digits2 === own.phoneDigits || digits2 === own.nationalDigits;
596
+ }
597
+ function ownValueKinds(text2, identity, options = {}) {
587
598
  const { own, emailHashes, phoneHashes } = ownMatcher(identity);
588
599
  const kinds = /* @__PURE__ */ new Set();
589
- const isPhone = (digits2) => digits2.includes(own.phoneDigits) || digits2.includes(own.nationalDigits) || own.extraPhones.includes(digits2);
590
600
  const addHash = (value) => {
591
601
  const bare = value.replace(/=+$/, "");
592
602
  if (emailHashes.has(bare)) kinds.add("email hash");
593
603
  if (phoneHashes.has(bare)) kinds.add("phone hash");
594
604
  };
595
- for (const c of candidates(text2)) {
605
+ for (const c of candidates(text2, options.literal)) {
596
606
  if (c.kind === "email") {
597
- const email = normalizeEmail(c.value);
598
- if (email.includes(own.email) || own.extraEmails.includes(email)) kinds.add("email");
607
+ if (isOwnEmail(c.value, own, c.fromBase64)) kinds.add("email");
599
608
  } else if (c.kind === "phone") {
600
- if (isPhone(c.value.replace(/\D/g, ""))) kinds.add("phone");
609
+ if (isOwnPhone(c.value.replace(/\D/g, ""), own, c.fromBase64)) kinds.add("phone");
601
610
  } else addHash(c.value.toLowerCase());
602
611
  }
603
- if (/^[+\d\s().-]+$/.test(text2) && isPhone(text2.replace(/\D/g, ""))) kinds.add("phone");
604
- const trimmed = text2.trim();
605
- addHash(trimmed);
606
- addHash(trimmed.toLowerCase());
612
+ if (/^[+\d\s().-]+$/.test(text2) && isOwnPhone(text2.replace(/\D/g, ""), own, false)) kinds.add("phone");
607
613
  for (const variant of variants(text2)) {
614
+ const trimmed = variant.trim();
615
+ addHash(trimmed);
616
+ addHash(trimmed.toLowerCase());
608
617
  for (const token of hasUrlEscapes(variant) ? [] : keyedDigests(variant)) addHash(token);
609
618
  }
610
619
  return kinds;
611
620
  }
612
621
  var matchers = /* @__PURE__ */ new WeakMap();
613
622
  function ownMatcher(identity) {
623
+ const signature = JSON.stringify([identity.email, identity.phone, identity.country, identity.extra ?? []]);
614
624
  let matcher = matchers.get(identity);
615
- if (!matcher) {
625
+ if (!matcher || matcher.signature !== signature) {
616
626
  const own = ownValues(identity);
617
627
  const phoneExtras = (identity.extra ?? []).filter((v) => /^[+\d\s().-]+$/.test(v) && own.extraPhones.includes(v.replace(/\D/g, "")));
618
628
  matcher = {
629
+ signature,
619
630
  own,
620
631
  emailHashes: fieldHashes(own.email, ...own.extraEmails),
621
632
  phoneHashes: fieldHashes("+" + own.phoneDigits, own.phoneDigits, ...phoneExtras, ...phoneExtras.map((v) => v.replace(/\D/g, "")), ...phoneExtras.map((v) => "+" + v.replace(/\D/g, "")))
@@ -633,12 +644,12 @@ function scan(text2, identity, options = {}) {
633
644
  };
634
645
  for (const c of candidates(text2)) {
635
646
  if (c.kind === "email") {
636
- if (normalizeEmail(c.value).includes(own.email) || own.extraEmails.includes(normalizeEmail(c.value))) continue;
647
+ if (isOwnEmail(c.value, own, c.fromBase64)) continue;
637
648
  add2("email", c.value);
638
649
  if (c.alternate) add2("email", c.alternate);
639
650
  } else if (c.kind === "phone") {
640
651
  const digits2 = c.value.replace(/\D/g, "");
641
- if (!digits2.includes(own.phoneDigits) && !digits2.includes(own.nationalDigits) && !own.extraPhones.includes(digits2)) add2("phone", c.value);
652
+ if (!isOwnPhone(digits2, own, c.fromBase64)) add2("phone", c.value);
642
653
  } else if (!own.hashes.has(c.value) && !options.stableHashes?.has(c.value) && !isNonPersonalKey(c.variant, c.index)) {
643
654
  add2("hash", c.value);
644
655
  }
@@ -651,6 +662,45 @@ function scan(text2, identity, options = {}) {
651
662
  return [...found.values()];
652
663
  }
653
664
 
665
+ // packages/core/src/canary.ts
666
+ var CANARY_NAMES = ["gclid", "gbraid", "wbraid", "fbclid", "msclkid", "ttclid"];
667
+ function canaryValues(seed, cell) {
668
+ const where2 = (cell ?? "run").toUpperCase();
669
+ return CANARY_NAMES.map((name) => ({ source: "urlParam", name, value: `TEST-${name.toUpperCase()}-${seed}-${where2}-0001` }));
670
+ }
671
+ var CLICK_ID_COOKIE = /^(?:GCL\.[^.]*\.|fb\.1\.\d+\.)(.+)$/;
672
+ function formsOf(value) {
673
+ const buffer = Buffer.from(value);
674
+ return [value, encodeURIComponent(value), buffer.toString("base64"), buffer.toString("base64url"), ...fieldHashes(value)];
675
+ }
676
+ function canaryPool(canaries, identity) {
677
+ const forms = /* @__PURE__ */ new Map();
678
+ const add2 = (name, value) => {
679
+ for (const form of formsOf(value)) if (!forms.has(form)) forms.set(form, name);
680
+ };
681
+ for (const { name, value } of canaries) add2(name, value);
682
+ if (identity) {
683
+ add2("email", identity.email);
684
+ add2("phone", identity.phone);
685
+ }
686
+ const nameOf2 = (text2) => {
687
+ const exact = forms.get(text2);
688
+ if (exact !== void 0) return exact;
689
+ const token = CLICK_ID_COOKIE.exec(text2)?.[1];
690
+ return token === void 0 ? void 0 : forms.get(token);
691
+ };
692
+ return {
693
+ forms,
694
+ match(text2) {
695
+ for (const reading of readings(text2)) {
696
+ const name = nameOf2(reading);
697
+ if (name !== void 0) return name;
698
+ }
699
+ return void 0;
700
+ }
701
+ };
702
+ }
703
+
654
704
  // packages/core/src/library.ts
655
705
  var LIBRARY_PATH = /(?:^|\/)(?:gtag\/js|fbevents\.js|signals\/config\/[^/]*)$/;
656
706
  function isLibraryLoadPath(pathname) {
@@ -684,7 +734,7 @@ var CONSENT_COMMANDS = /* @__PURE__ */ new Set(["default", "update"]);
684
734
  function argumentsListOf(args) {
685
735
  const [item] = args;
686
736
  if (args.length !== 1 || typeof item !== "object" || item === null || Array.isArray(item)) return void 0;
687
- const keys = Object.keys(item);
737
+ const keys = Object.keys(item).filter((k) => !k.startsWith("gtm."));
688
738
  if (keys.length < 1 || keys.length > MAX_ARGUMENTS || !keys.every((k, i) => k === String(i))) return void 0;
689
739
  const list3 = keys.map((_, i) => item[String(i)]);
690
740
  return typeof list3[0] === "string" ? list3 : void 0;
@@ -970,6 +1020,18 @@ function maskValuePath(path, mask) {
970
1020
  return maskSegments(path.slice(0, prefix.index)) + prefix[0] + maskSegments(path.slice(end));
971
1021
  }
972
1022
 
1023
+ // packages/decoders/src/page-fields.ts
1024
+ var PINTEREST_PAGE = "ad.loc";
1025
+ var PAGE_FIELDS = {
1026
+ ga4: { page: ["dl"], referrer: ["dr"] },
1027
+ "google-ads": { page: ["url", "dl"], referrer: ["ref"] },
1028
+ meta: { page: ["dl"], referrer: ["rl"] },
1029
+ "meta-capi": { page: ["event_source_url"], referrer: [] },
1030
+ pinterest: { page: [PINTEREST_PAGE], referrer: [] },
1031
+ sgtm: { page: ["page_location"], referrer: [] },
1032
+ tracker: { page: ["dl", "page_location", "page_url", "url", "u", "loc", "href"], referrer: [] }
1033
+ };
1034
+
973
1035
  // packages/decoders/src/base64.ts
974
1036
  var ALPHABET2 = /^[A-Za-z0-9+/_-]+={0,2}$/;
975
1037
  function decodeBase64Text(value) {
@@ -1060,6 +1122,16 @@ function gcdSignals(gcd) {
1060
1122
  });
1061
1123
  return out;
1062
1124
  }
1125
+ var SAME_STATE_PAIRS = /* @__PURE__ */ new Set(["pq", "qp", "tv", "vt"]);
1126
+ function sameGcdState(a, b) {
1127
+ if (a.length < 9 || a.length !== b.length) return false;
1128
+ const signalIndexes = GCD_SIGNALS.map((_, i) => 2 + 2 * i);
1129
+ for (let i = 0; i < a.length; i++) {
1130
+ if (a[i] === b[i]) continue;
1131
+ if (!signalIndexes.includes(i) || !SAME_STATE_PAIRS.has(a[i] + b[i])) return false;
1132
+ }
1133
+ return true;
1134
+ }
1063
1135
  function gcdLetters(gcd) {
1064
1136
  if (!gcdSignals(gcd)) return void 0;
1065
1137
  return GCD_SIGNALS.map((_, i) => gcdLetterAt(gcd, i) in GCD_LETTERS ? gcdLetterAt(gcd, i) : "?");
@@ -1142,7 +1214,7 @@ var ga4 = {
1142
1214
  event: p.get("en"),
1143
1215
  consent: decodeGa4Consent(p),
1144
1216
  ids,
1145
- page: p.get("dl"),
1217
+ page: p.get(PAGE_FIELDS.ga4.page[0]),
1146
1218
  transport: transport(req.resourceType),
1147
1219
  params: { ...eventParams(p), ...tid ? { tid } : {} }
1148
1220
  }, queryEntries(p), complete);
@@ -1221,7 +1293,7 @@ var meta = {
1221
1293
  raw: {}
1222
1294
  },
1223
1295
  ids,
1224
- page: p.get("dl"),
1296
+ page: p.get(PAGE_FIELDS.meta.page[0]),
1225
1297
  transport: req.resourceType === "ping" ? "beacon" : req.resourceType,
1226
1298
  params
1227
1299
  }, queryEntries(p), bodyComplete(req))
@@ -1310,7 +1382,7 @@ function decodeItem(item, req, pixel, newHitId, complete) {
1310
1382
  event: str(item.event_name) ?? null,
1311
1383
  consent: { ads: "unknown", analytics: "unknown", adUserData: "unknown", adPersonalization: "unknown", raw: {} },
1312
1384
  ids,
1313
- page: str(item.event_source_url) ?? null,
1385
+ page: str(item[PAGE_FIELDS["meta-capi"].page[0]]) ?? null,
1314
1386
  transport: req.resourceType === "ping" ? "beacon" : req.resourceType,
1315
1387
  params
1316
1388
  }, jsonEntries(item), complete);
@@ -1431,7 +1503,7 @@ var pinterest = {
1431
1503
  raw: {}
1432
1504
  },
1433
1505
  ids,
1434
- page: text(ad.loc) ?? null,
1506
+ page: text(ad[PAGE_FIELDS.pinterest.page[0].slice("ad.".length)]) ?? null,
1435
1507
  transport: req.resourceType === "ping" ? "beacon" : req.resourceType,
1436
1508
  params
1437
1509
  }, entries, complete)
@@ -1519,7 +1591,7 @@ var googleAds = {
1519
1591
  event: p.get("en") ?? (REMARKETING.test(ping.url.pathname) ? "remarketing" : "conversion"),
1520
1592
  consent: decodeGa4Consent(p),
1521
1593
  ids,
1522
- page: p.get("url") ?? p.get("dl"),
1594
+ page: p.get(PAGE_FIELDS["google-ads"].page[0]) ?? p.get(PAGE_FIELDS["google-ads"].page[1]),
1523
1595
  transport: req.resourceType === "ping" ? "beacon" : req.resourceType,
1524
1596
  params
1525
1597
  }, queryEntries(p), bodyComplete(req))
@@ -1572,12 +1644,12 @@ function dataRequest(req, viaLoader) {
1572
1644
  if (Object.keys(parseDtdc(p.get("dtdc"))).length > 0) return url;
1573
1645
  if (p.has("v") && (p.has("event") || p.has("en"))) return url;
1574
1646
  const body = req.method === "POST" ? parseObject(req.postData) : {};
1575
- if (str2(body.event_name) && str2(body.page_location)) return url;
1647
+ if (str2(body.event_name) && str2(body[PAGE_FIELDS.sgtm.page[0]])) return url;
1576
1648
  return isCutDataBody(req) ? url : void 0;
1577
1649
  }
1578
1650
  function isCutDataBody(req) {
1579
1651
  if (req.method !== "POST" || req.postData === null || bodyComplete(req) || !req.postData.startsWith("{")) return false;
1580
- return /"event_name"\s*:/.test(req.postData) && /"page_location"\s*:/.test(req.postData);
1652
+ return /"event_name"\s*:/.test(req.postData) && new RegExp(`"${PAGE_FIELDS.sgtm.page[0]}"\\s*:`).test(req.postData);
1581
1653
  }
1582
1654
  var sgtmDataClient = {
1583
1655
  name: "sgtm-data-client",
@@ -1615,7 +1687,7 @@ var sgtmDataClient = {
1615
1687
  event: p.get("event") ?? p.get("en") ?? str2(dtdc.event_name) ?? str2(body.event_name) ?? null,
1616
1688
  consent: decodeGa4Consent(p),
1617
1689
  ids,
1618
- page: str2(dtdc.page_location) ?? str2(body.page_location) ?? null,
1690
+ page: str2(dtdc[PAGE_FIELDS.sgtm.page[0]]) ?? str2(body[PAGE_FIELDS.sgtm.page[0]]) ?? null,
1619
1691
  transport: req.resourceType === "ping" ? "beacon" : req.resourceType,
1620
1692
  params
1621
1693
  }, entries, complete)
@@ -1708,7 +1780,6 @@ function parseTrackerList(json) {
1708
1780
  // packages/decoders/src/tracker.ts
1709
1781
  var LOADS = /* @__PURE__ */ new Set(["script", "stylesheet", "font", "document"]);
1710
1782
  var EVENT_PARAMS = ["event", "ev", "event_name", "en", "evt", "ea"];
1711
- var PAGE_PARAMS = ["dl", "page_location", "page_url", "url", "u", "loc", "href"];
1712
1783
  function trackerCollection(req, list3 = trackerList) {
1713
1784
  const entry = trackerFor(req, list3);
1714
1785
  if (!entry) return void 0;
@@ -1745,7 +1816,7 @@ function decodeTracker(req, list3 = trackerList, newHitId = defaultHitId) {
1745
1816
  event: firstParam(params, EVENT_PARAMS),
1746
1817
  consent: { ads: "unknown", analytics: "unknown", adUserData: "unknown", adPersonalization: "unknown", raw: {} },
1747
1818
  ids: {},
1748
- page: firstParam(params, PAGE_PARAMS) ?? (isSandboxPageUrl(req.frameUrl) ? null : req.frameUrl),
1819
+ page: firstParam(params, PAGE_FIELDS.tracker.page) ?? (isSandboxPageUrl(req.frameUrl) ? null : req.frameUrl),
1749
1820
  transport: "tracker-list",
1750
1821
  params: {}
1751
1822
  }, [...queryEntries(params), ...body.entries], body.parsed && bodyComplete(req))
@@ -2158,7 +2229,7 @@ function parseViewportText(text2) {
2158
2229
  return isViewportSide(viewport.width) && isViewportSide(viewport.height) ? viewport : void 0;
2159
2230
  }
2160
2231
  var VIEWPORT_HINT = `a size such as 390x844, with each side from ${VIEWPORT_MIN} to ${VIEWPORT_MAX}`;
2161
- var BUILTIN_NAMES = ["unknownDestination", "sandboxPageUrl", "possibleRealData", "deniedIdentifiers", "earlyIdentifiers", "consentModeSetup", "earlyIdentityPush", "idHandover", "serverContainerRejected"];
2232
+ var BUILTIN_NAMES = ["unknownDestination", "sandboxPageUrl", "possibleRealData", "deniedIdentifiers", "earlyIdentifiers", "consentModeSetup", "earlyIdentityPush", "idHandover", "serverContainerRejected", "identifierRoute"];
2162
2233
  var SEVERITIES = ["fail", "warn"];
2163
2234
  var IDENTITY_FIELDS = ["firstName", "lastName", "email", "phone", "address1", "city", "zip", "country"];
2164
2235
  var ScenarioError = class extends Error {
@@ -2186,7 +2257,7 @@ var NETWORKS = ["stub", "server"];
2186
2257
  var CONSENT_ANSWERS = ["accept", "reject", "none", "withdraw"];
2187
2258
  var STEP_KINDS = ["visit", "click", "fill", "select", "consent", "wait", "addToCart", "evaluate", "checkpoint", "handoff", "payment"];
2188
2259
  var TOP_KEYS = ["start", "vars", "identity", "steps", "expect", "options"];
2189
- var OPTION_KEYS = ["network", "seed", "consentTimeout", "graceWindow", "optionalTimeout", "allowUnknownDestination", "firstPartyHosts", "platformHosts", "cartRequest", "unloadGapIgnore", "dataLayerNames", "builtins", "identifierFields", "serverHosts", "viewport"];
2260
+ var OPTION_KEYS = ["network", "seed", "consentTimeout", "graceWindow", "optionalTimeout", "allowUnknownDestination", "firstPartyHosts", "identifierRouteAllow", "platformHosts", "cartRequest", "unloadGapIgnore", "dataLayerNames", "builtins", "identifierFields", "serverHosts", "viewport", "withdrawWith", "canaries"];
2190
2261
  var MAX_DATALAYER_NAMES = 8;
2191
2262
  var DATALAYER_NAME_PATTERN = /^[A-Za-z_$][\w$]{0,63}$/;
2192
2263
  var NEVER_TRAPPED_NAMES = ["location", "Shopify", "__proto__", "constructor", "prototype"];
@@ -2227,22 +2298,22 @@ function parseCount(value) {
2227
2298
  if (!m || typeof value !== "string" && typeof value !== "number") return void 0;
2228
2299
  return { op: m[1] ?? "=", n: Number(m[2]) };
2229
2300
  }
2230
- function countHolds(count, actual) {
2231
- switch (count.op) {
2301
+ function countHolds(count2, actual) {
2302
+ switch (count2.op) {
2232
2303
  case ">=":
2233
- return actual >= count.n;
2304
+ return actual >= count2.n;
2234
2305
  case ">":
2235
- return actual > count.n;
2306
+ return actual > count2.n;
2236
2307
  case "<=":
2237
- return actual <= count.n;
2308
+ return actual <= count2.n;
2238
2309
  case "<":
2239
- return actual < count.n;
2310
+ return actual < count2.n;
2240
2311
  case "=":
2241
- return actual === count.n;
2312
+ return actual === count2.n;
2242
2313
  }
2243
2314
  }
2244
- function describeCount(count) {
2245
- return count.op === "=" ? String(count.n) : `${count.op}${count.n}`;
2315
+ function describeCount(count2) {
2316
+ return count2.op === "=" ? String(count2.n) : `${count2.op}${count2.n}`;
2246
2317
  }
2247
2318
  function parseOptions(raw, path, fail, { keys = OPTION_KEYS, echo = true } = {}) {
2248
2319
  const options = {};
@@ -2286,6 +2357,12 @@ function parseOptions(raw, path, fail, { keys = OPTION_KEYS, echo = true } = {})
2286
2357
  } else if (k === "viewport") {
2287
2358
  if (isMap(v) && Object.keys(v).length === 2 && isViewportSide(v.width) && isViewportSide(v.height)) options.viewport = { width: v.width, height: v.height };
2288
2359
  else fail(p, `must be { width, height }, integers from ${VIEWPORT_MIN} to ${VIEWPORT_MAX}. The preset "mobile" does not exist`);
2360
+ } else if (k === "withdrawWith") {
2361
+ if (typeof v === "string" && v.trim() !== "") options.withdrawWith = v;
2362
+ else fail(p, 'must be a selector such as "#cookie-settings"');
2363
+ } else if (k === "canaries") {
2364
+ if (typeof v === "boolean") options.canaries = v;
2365
+ else fail(p, "must be true or false");
2289
2366
  } else if (k === "identifierFields") {
2290
2367
  if (!Array.isArray(v) || v.length === 0 || !v.every((x) => typeof x === "string" && x !== "")) fail(p, "must be a non-empty list of field names or globs such as user_data.*");
2291
2368
  else if (v.some((x) => x.length > MAX_FIELD_NAME)) fail(p, `field names are at most ${MAX_FIELD_NAME} characters`);
@@ -2306,6 +2383,9 @@ function parseOptions(raw, path, fail, { keys = OPTION_KEYS, echo = true } = {})
2306
2383
  } else if (k === "firstPartyHosts") {
2307
2384
  if (isHostList(v)) options.firstPartyHosts = v;
2308
2385
  else fail(p, `must be a list of hosts${HOST_HINT}`);
2386
+ } else if (k === "identifierRouteAllow") {
2387
+ if (isHostList(v)) options.identifierRouteAllow = v;
2388
+ else fail(p, `must be a list of hosts${HOST_HINT}`);
2309
2389
  } else {
2310
2390
  const ms = durationAt(v, p, fail);
2311
2391
  if (ms === void 0) continue;
@@ -2686,8 +2766,11 @@ function parseScenario(text2, extraVendorKeys = []) {
2686
2766
  };
2687
2767
  for (const [key, raw2] of Object.entries(v)) {
2688
2768
  const p = [...path, key];
2689
- if (!PUSH_SELECTOR_KEYS.includes(key)) fail(p, `unknown key, expected one of ${PUSH_SELECTOR_KEYS.join(", ")}`);
2690
- else if (key === "event") {
2769
+ if (!PUSH_SELECTOR_KEYS.includes(key)) {
2770
+ const message = `unknown key, expected one of ${PUSH_SELECTOR_KEYS.join(", ")}`;
2771
+ if (pathProblem(key) === void 0) fail(p, message);
2772
+ else issues.push(`line ${lineOf(p)}: ${[...path, OTHER_NAME].reduce((acc, x) => typeof x === "number" ? `${acc}[${x}]` : acc ? `${acc}.${x}` : x, "")}: ${message}`);
2773
+ } else if (key === "event") {
2691
2774
  if (typeof raw2 === "string" && raw2 !== "" && raw2.length <= MAX_PUSH_PATH && isEventLabel(raw2)) event = raw2;
2692
2775
  else fail(p, "must be an event name as the --json push shapes show it, such as purchase. A name that reads (other) there cannot be matched");
2693
2776
  } else if (key === "has") {
@@ -2698,7 +2781,7 @@ function parseScenario(text2, extraVendorKeys = []) {
2698
2781
  const entries = isMap(raw2) ? Object.entries(raw2) : [];
2699
2782
  if (entries.length === 0 || entries.length > MAX_PUSH_PATHS) fail(p, `must be a mapping of 1 to ${MAX_PUSH_PATHS} key paths to a type, such as ecommerce.value: number`);
2700
2783
  else if (paths(key, entries.map(([k]) => k))) {
2701
- const types = {};
2784
+ const types = /* @__PURE__ */ Object.create(null);
2702
2785
  for (const [k, t] of entries) {
2703
2786
  if (typeof t === "string" && PUSH_TYPES.includes(t)) types[k] = t;
2704
2787
  else fail([...p, k], `must be one of ${PUSH_TYPES.join(", ")}`);
@@ -2903,6 +2986,48 @@ function realDataWarning(value, country) {
2903
2986
  return kind === "phone" ? phoneWarning(value, country) : kind && `looks like a real ${kind}`;
2904
2987
  }
2905
2988
 
2989
+ // packages/expect/src/consent-matrix.ts
2990
+ var CONSENT_STATES = ["accept", "reject", "none", "withdraw"];
2991
+ function isConsentState(value) {
2992
+ return CONSENT_STATES.includes(value);
2993
+ }
2994
+ function ownConsentState(scenario) {
2995
+ const first = scenario.steps.find((s) => s.kind === "consent");
2996
+ return first?.kind === "consent" ? first.value : void 0;
2997
+ }
2998
+ function ruleCount(scenario) {
2999
+ return scenario.expect.must.length + scenario.expect.mustNot.length;
3000
+ }
3001
+ function withConsent(scenario, state) {
3002
+ const at = scenario.steps.findIndex((s) => s.kind === "consent");
3003
+ const expect = state === ownConsentState(scenario) ? { must: [...scenario.expect.must], mustNot: [...scenario.expect.mustNot] } : { must: [], mustNot: [] };
3004
+ if (at < 0) return { ...scenario, steps: [...scenario.steps], expect };
3005
+ const first = scenario.steps[at];
3006
+ const withdrawWith = scenario.options.withdrawWith;
3007
+ const inserted = state === "withdraw" && withdrawWith !== void 0 ? [
3008
+ { kind: "consent", value: "accept", label: first.label, line: first.line },
3009
+ { kind: "wait", value: 1e3, label: "", line: first.line },
3010
+ { kind: "click", value: withdrawWith, label: "", line: first.line },
3011
+ { kind: "consent", value: "withdraw", label: "", line: first.line }
3012
+ ] : [{ kind: "consent", value: state, label: first.label, line: first.line }];
3013
+ const shift = inserted.length - 1;
3014
+ const moved = [...scenario.steps.slice(0, at), ...inserted, ...scenario.steps.slice(at + 1)].map((step, i) => {
3015
+ const was = i < at ? i : i - shift;
3016
+ const inserting = i >= at && i < at + inserted.length;
3017
+ const renamed = step.label === "" || !inserting && step.label === `${step.kind}-${was + 1}`;
3018
+ return { step, renamed };
3019
+ });
3020
+ const taken = new Set(moved.filter((m) => !m.renamed).map((m) => m.step.label));
3021
+ const steps = moved.map(({ step, renamed }, i) => {
3022
+ if (!renamed) return step;
3023
+ let label = `${step.kind}-${i + 1}`;
3024
+ for (let n = 2; taken.has(label); n++) label = `${step.kind}-${i + 1}-${n}`;
3025
+ taken.add(label);
3026
+ return { ...step, label };
3027
+ });
3028
+ return { ...scenario, steps, expect };
3029
+ }
3030
+
2906
3031
  // packages/expect/src/consent-mode-setup.ts
2907
3032
  var CONSENT_MODE_URL = "https://developers.google.com/tag-platform/security/guides/consent";
2908
3033
  var GOOGLE_VENDORS = /* @__PURE__ */ new Set(["ga4", "google-ads"]);
@@ -2981,6 +3106,112 @@ function consentModeSetup(hits, dataLayer) {
2981
3106
  return { pass: true, evidence: [], message: `Expected Consent Mode signals to be set on Google hits, found every signal set (gcd letters: ${lettersNote(letterSets)}).${missingNote}` };
2982
3107
  }
2983
3108
 
3109
+ // packages/expect/src/identifier-route.ts
3110
+ var MAX_LINES = 5;
3111
+ var NOT_SEARCHED = "headers, including Referer and Cookie, not searched";
3112
+ function stateForbids(state) {
3113
+ const known = consentFields.map((f) => state[f]).filter((v) => v !== "unknown");
3114
+ if (known.length === 0 || known.every((v) => v === "denied")) return true;
3115
+ return state.analytics === "denied" || state.adUserData === "denied";
3116
+ }
3117
+ function epochForbids(epoch) {
3118
+ if (!epoch) return true;
3119
+ if (epoch.label === "granted") return false;
3120
+ if (epoch.label === "mixed") return stateForbids(epoch.state);
3121
+ return true;
3122
+ }
3123
+ function hitForbids(hit, epochs, grace) {
3124
+ const own = GOOGLE_VENDORS.has(hit.vendor) && consentFields.some((f) => hit.consent[f] !== "unknown");
3125
+ return own ? stateForbids(effectiveConsentAt(hit, epochs, grace)) : epochForbids(epochForHit(epochs, hit.t, grace));
3126
+ }
3127
+ function judgeServerCall(hits, hitsById, epochs, grace) {
3128
+ const linked = hits.flatMap((h) => {
3129
+ const browser = h.via ? hitsById.get(h.via.hitId) : void 0;
3130
+ return h.via && browser ? [{ confidence: h.via.confidence, browser }] : [];
3131
+ });
3132
+ const exact = linked.filter((l) => l.confidence === "exact");
3133
+ if (exact.some((l) => hitForbids(l.browser, epochs, grace))) return { level: "fail" };
3134
+ if (hits.length > 0 && exact.length === hits.length) return { level: "ok" };
3135
+ if (hits.length > 0 && linked.length === hits.length) return { level: "warn", note: "serverSendProbableLink" };
3136
+ return { level: "warn", note: "serverSendUnlinked" };
3137
+ }
3138
+ function judge(route, request, hits, hitsById, epochs, grace) {
3139
+ const pageOnly = route.kind === "pageUrl";
3140
+ const failLevel = pageOnly ? "warn" : "fail";
3141
+ if (request?.captured === "serverContainer") {
3142
+ const at = epochForHit(epochs, request.t, grace);
3143
+ const upTo = at ? epochs.slice(0, epochs.indexOf(at) + 1) : [];
3144
+ if (upTo.every(epochForbids)) return { level: failLevel };
3145
+ const verdict = judgeServerCall(hits, hitsById, epochs, grace);
3146
+ return verdict.level === "fail" ? { level: failLevel } : verdict;
3147
+ }
3148
+ const forbidden = hits.length > 0 ? hits.some((h) => hitForbids(h, epochs, grace)) : epochForbids(request ? epochForHit(epochs, request.t, grace) : void 0);
3149
+ return { level: forbidden ? failLevel : "ok" };
3150
+ }
3151
+ function routeLine(route, level, note) {
3152
+ const from = route.source.source === "identity" ? `identity ${route.source.name}` : `url param ${route.source.name}`;
3153
+ const base2 = `${from} -> request to ${route.sink.host}, param ${route.sink.field}, ${route.sink.transform}`;
3154
+ if (note === "serverSendUnlinked") return `${base2} (server container call, consent was granted before it)`;
3155
+ if (note === "serverSendProbableLink") return `${base2} (server container call, probable link)`;
3156
+ return route.kind === "pageUrl" && level === "warn" ? `${base2} (page URL only)` : base2;
3157
+ }
3158
+ var count = (text2, re) => Number(re.exec(text2)?.[1] ?? 0);
3159
+ function searchedText(search) {
3160
+ const requests = /Searched (\d+) requests?/.exec(search.detail)?.[1];
3161
+ const reasons = [
3162
+ [count(search.detail, /compressed or binary body (\d+)/), "compressed or binary body"],
3163
+ [count(search.detail, /body cut at 64 KiB (\d+)/), "body cut at 64 KiB"],
3164
+ [count(search.detail, /net-log request with no body (\d+)/), "net-log request with no body"]
3165
+ ];
3166
+ const parts = reasons.filter(([n]) => n > 0).map(([n, what]) => `${n} ${what}`);
3167
+ const skipped = `skipped ${search.recordIds.length}${parts.length > 0 ? ` (${parts.join(", ")})` : ""}`;
3168
+ const forms = /\bas (plain text.+?)\. Searched:/.exec(search.detail)?.[1];
3169
+ if (requests === void 0 || forms === void 0) return `${search.detail} ${NOT_SEARCHED}; ${skipped}.`;
3170
+ return `searched forms (${forms}) in the URL, body and decoded fields of ${requests} request${requests === "1" ? "" : "s"}; ${NOT_SEARCHED}; ${skipped}.`;
3171
+ }
3172
+ function identifierRoute(records, graceMs, override, allow = []) {
3173
+ const search = records.find((r) => r.type === "flag" && r.kind === "canarySearch");
3174
+ if (!search) return void 0;
3175
+ const epochs = records.filter((r) => r.type === "consentEpoch").sort((a, b) => a.startT - b.startT);
3176
+ const requests = new Map(records.filter((r) => r.type === "request").map((r) => [r.id, r]));
3177
+ const hitsByRequest = /* @__PURE__ */ new Map();
3178
+ const hitsById = /* @__PURE__ */ new Map();
3179
+ for (const r of records) if (r.type === "hit") hitsById.set(r.id, r);
3180
+ for (const r of records) if (r.type === "hit") hitsByRequest.set(r.requestId, [...hitsByRequest.get(r.requestId) ?? [], r]);
3181
+ const routes2 = records.filter((r) => r.type === "flag" && r.kind === "identifierRoute" && r.route !== void 0);
3182
+ const findings = [];
3183
+ const allowedByHost = /* @__PURE__ */ new Map();
3184
+ let judged = 0;
3185
+ for (const { route } of routes2) {
3186
+ if (allow.length > 0 && hostMatches(route.sink.host, allow)) {
3187
+ allowedByHost.set(route.sink.host, (allowedByHost.get(route.sink.host) ?? 0) + 1);
3188
+ continue;
3189
+ }
3190
+ judged++;
3191
+ const requestId = route.sink.requestId;
3192
+ const { level, note: note2 } = judge(route, requests.get(requestId), hitsByRequest.get(requestId) ?? [], hitsById, epochs, graceMs);
3193
+ if (level !== "ok") findings.push({ line: routeLine(route, level, note2), level, requestId, note: note2 });
3194
+ }
3195
+ const allowedText = allowedByHost.size === 0 ? "" : ` (allowed by identifierRouteAllow: ${[...allowedByHost].map(([host, n]) => `${n} route${n === 1 ? "" : "s"} to ${host}`).join(", ")})`;
3196
+ const sorted = [...findings.filter((f) => f.level === "fail"), ...findings.filter((f) => f.level === "warn")];
3197
+ if (sorted.length === 0) {
3198
+ const allowed = judged;
3199
+ const head = allowed > 0 ? `No planted value reached a sink while consent forbade it (${allowed} route${allowed === 1 ? "" : "s"} allowed by consent); ` : "No planted value found in the ";
3200
+ return { pass: true, evidence: [], message: `${head}${searchedText(search)}${allowedText}`, severity: override ?? "fail" };
3201
+ }
3202
+ const failing = sorted.some((f) => f.level === "fail");
3203
+ const shown2 = sorted.slice(0, MAX_LINES).map((f) => f.line).join("; ");
3204
+ const more = sorted.length > MAX_LINES ? `; and ${sorted.length - MAX_LINES} more` : "";
3205
+ const note = failing ? void 0 : sorted.find((f) => f.note === "serverSendUnlinked")?.note ?? sorted.find((f) => f.note)?.note;
3206
+ return {
3207
+ pass: false,
3208
+ evidence: [...new Set(sorted.map((f) => f.requestId))],
3209
+ message: `Expected no planted value to reach a sink while consent forbids it, found ${sorted.length}: ${shown2}${more}. Headers, including Referer and Cookie, were not searched.${allowedText}`,
3210
+ severity: failing ? override ?? "fail" : "warn",
3211
+ ...note && { note }
3212
+ };
3213
+ }
3214
+
2984
3215
  // packages/expect/src/early-identity-push.ts
2985
3216
  var MAX_DEPTH3 = 8;
2986
3217
  var MAX_LISTED2 = 5;
@@ -3006,12 +3237,12 @@ var holdsLocalPart = (key, identity) => {
3006
3237
  };
3007
3238
  var safeKey2 = (key, identity) => {
3008
3239
  if (guardFieldName(key) !== key || isValueSegment(key)) return OTHER_NAME;
3009
- return holdsLocalPart(key, identity) || ownValueKinds(key, identity).size > 0 ? OTHER_NAME : key;
3240
+ return holdsLocalPart(key, identity) || ownValueKinds(key, identity, { literal: true }).size > 0 ? OTHER_NAME : key;
3010
3241
  };
3011
3242
  function ownLeaves(value, path, key, identity, depth, out) {
3012
3243
  if (depth > MAX_DEPTH3) return;
3013
3244
  if (typeof value === "string" || typeof value === "number") {
3014
- const kinds = ownValueKinds(`${key}=${value}`, identity);
3245
+ const kinds = ownValueKinds(`${key}=${value}`, identity, { literal: true });
3015
3246
  for (const k of ownValueKinds(String(value), identity)) kinds.add(k);
3016
3247
  if (kinds.size === 0) return;
3017
3248
  const name = path || "(value)";
@@ -3025,7 +3256,16 @@ function ownLeaves(value, path, key, identity, depth, out) {
3025
3256
  for (const item of value) ownLeaves(item, `${path}[]`, key, identity, depth + 1, out);
3026
3257
  return;
3027
3258
  }
3028
- for (const [k, child] of Object.entries(value)) ownLeaves(child, path === "" ? safeKey2(k, identity) : `${path}.${safeKey2(k, identity)}`, k, identity, depth + 1, out);
3259
+ for (const [k, child] of Object.entries(value)) {
3260
+ const childPath = path === "" ? safeKey2(k, identity) : `${path}.${safeKey2(k, identity)}`;
3261
+ const keyKinds = ownValueKinds(k, identity, { literal: true });
3262
+ if (keyKinds.size > 0) {
3263
+ const found = out.get(childPath) ?? /* @__PURE__ */ new Set();
3264
+ for (const kind of keyKinds) found.add(kind);
3265
+ out.set(childPath, found);
3266
+ }
3267
+ ownLeaves(child, childPath, k, identity, depth + 1, out);
3268
+ }
3029
3269
  }
3030
3270
  var withoutConsent = (epoch) => epoch.label === "mixed" ? epoch.state.adUserData === "denied" || epoch.state.analytics === "denied" : ["undecided", "denied", "withdrawn"].includes(epoch.label);
3031
3271
  function earlyIdentityPush(pushes, place, identity) {
@@ -3108,10 +3348,13 @@ function idHandover(hits, requests) {
3108
3348
  flag2(`${tid}: client ID differs between ${a.label} and ${b.label}`, a, b);
3109
3349
  continue;
3110
3350
  }
3111
- const sidsOf = (c) => new Set(c.seen.filter((s) => shared.has(s.cid) && s.sid).map((s) => s.sid));
3112
- const sidsA = sidsOf(a);
3113
- const sidsB = sidsOf(b);
3114
- if (sidsA.size > 0 && sidsB.size > 0 && ![...sidsA].some((v) => sidsB.has(v))) flag2(`${tid}: session ID differs between ${a.label} and ${b.label}`, a, b);
3351
+ const sidsOf = (c, cid) => new Set(c.seen.filter((s) => s.cid === cid && s.sid).map((s) => s.sid));
3352
+ const differs = [...shared].some((cid) => {
3353
+ const sidsA = sidsOf(a, cid);
3354
+ const sidsB = sidsOf(b, cid);
3355
+ return sidsA.size > 0 && sidsB.size > 0 && ![...sidsA].some((v) => sidsB.has(v));
3356
+ });
3357
+ if (differs) flag2(`${tid}: session ID differs between ${a.label} and ${b.label}`, a, b);
3115
3358
  }
3116
3359
  }
3117
3360
  }
@@ -3239,23 +3482,23 @@ function evaluatePushRule(rule, input) {
3239
3482
  }
3240
3483
  }
3241
3484
  const holders = matchers2.length ? selected.filter((p) => matchers2.every((m) => holdsPath(p, m))) : selected;
3242
- const count = rule.count ?? { op: ">=", n: 1 };
3243
- const pass = countHolds(count, holders.length);
3485
+ const count2 = rule.count ?? { op: ">=", n: 1 };
3486
+ const pass = countHolds(count2, holders.length);
3244
3487
  const typed = sel.types ? ` with types ${Object.entries(sel.types).map(([path, type]) => `${path}: ${type}`).join(", ")}` : "";
3245
3488
  const holding = `${sel.has ? ` holding ${sel.has.join(", ")}` : ""}${typed}`;
3246
- const unseenPushCouldBreak = sel.types !== void 0 || count.op === "<=" || count.op === "<" || count.op === "=";
3489
+ const unseenPushCouldBreak = sel.types !== void 0 || count2.op === "<=" || count2.op === "<" || count2.op === "=";
3247
3490
  if (pass && input.hookIncomplete && unseenPushCouldBreak) {
3248
3491
  return {
3249
3492
  pass: false,
3250
3493
  evidence: holders.map((p) => p.id),
3251
- message: `Expected ${describeCount(count)} ${subject}${holding}${where2}, found ${holders.length} of ${selected.length} (${before}), but the pushes could not all be read: the dataLayer hook is incomplete here, so a push may have been missed.`,
3494
+ message: `Expected ${describeCount(count2)} ${subject}${holding}${where2}, found ${holders.length} of ${selected.length} (${before}), but the pushes could not all be read: the dataLayer hook is incomplete here, so a push may have been missed.`,
3252
3495
  severity: "warn"
3253
3496
  };
3254
3497
  }
3255
3498
  return {
3256
3499
  pass,
3257
3500
  evidence: (pass ? holders : selected).map((p) => p.id),
3258
- message: `Expected ${describeCount(count)} ${subject}${holding}${where2}, found ${holders.length} of ${selected.length} (${before}).`
3501
+ message: `Expected ${describeCount(count2)} ${subject}${holding}${where2}, found ${holders.length} of ${selected.length} (${before}).`
3259
3502
  };
3260
3503
  }
3261
3504
 
@@ -3314,19 +3557,19 @@ function evaluateTagRule(rule, input) {
3314
3557
  narrowed.push(text2);
3315
3558
  }
3316
3559
  const statuses = selector.status && new Set(selector.status);
3317
- const byName = selector.name ? globToRegExp(selector.name) : void 0;
3560
+ const byName2 = selector.name ? globToRegExp(selector.name) : void 0;
3318
3561
  const matches = [];
3319
3562
  const unknown = /* @__PURE__ */ new Set();
3320
3563
  let unknownEntries = 0;
3321
3564
  for (const report of kept)
3322
3565
  for (const tag of report.tags) {
3323
3566
  if (statuses && !statuses.has(tag.status)) continue;
3324
- if (byName) {
3567
+ if (byName2) {
3325
3568
  const named = nameOf(report, tag, input.expected);
3326
3569
  if (!named) {
3327
3570
  unknown.add(report.id);
3328
3571
  unknownEntries += 1;
3329
- } else if (byName.test(named.name)) matches.push({ report, id: tag.id, name: named.name });
3572
+ } else if (byName2.test(named.name)) matches.push({ report, id: tag.id, name: named.name });
3330
3573
  } else if (tag.id === selector.id) matches.push({ report, id: tag.id, name: nameOf(report, tag, input.expected)?.name ?? null });
3331
3574
  }
3332
3575
  const want = rule.kind === "must" ? rule.count ?? { op: ">=", n: 1 } : { op: "=", n: 0 };
@@ -3420,22 +3663,30 @@ function evaluate(records, scenario, options = {}) {
3420
3663
  ...settled.note && { note: settled.note }
3421
3664
  });
3422
3665
  };
3666
+ const containerRan = Boolean(runRecord && (runRecord.serverContainer || runRecord.testServerContainer) && !runRecord.serverContainer?.error);
3667
+ const rejected = containerRan ? serverContainerRejected([...ctx.requests.values()], ctx.responses, scenario.options.serverHosts ?? []) : void 0;
3423
3668
  for (const kind of ["mustNot", "must"])
3424
3669
  for (const rule of scenario.expect[kind]) {
3425
3670
  const outcome = evaluateRule(rule, ctx);
3426
3671
  const { pass, evidence, message } = outcome;
3672
+ const ownNote = outcome.note === "nestedNameOnly" ? void 0 : outcome.note;
3673
+ const absence = kind === "must" ? !pass : pass;
3674
+ if (rejected && !rejected.pass && absence && (kind === "mustNot" || outcome.absent) && !ownNote && rule.filter.sentBy !== "browser" && !rule.tag && !rule.dataLayer && !rule.cookie) {
3675
+ add2(`${kind}: ${rule.description}`, false, evidence, REJECTED_MESSAGE, "warn", "serverContainerRejected");
3676
+ continue;
3677
+ }
3427
3678
  const passes = (c) => evaluateRuleHits(rule, c).pass;
3428
3679
  const scoped = !rule.tag && !rule.dataLayer && isScoped(rule);
3429
3680
  const failureRests = scoped && !pass && failureRestsOnProbableLink(ctx, passes, rule);
3430
- const ownNote = outcome.note === "nestedNameOnly" ? void 0 : outcome.note;
3431
3681
  const note = ownNote ?? (pass && scoped && passRestsOnProbableLink(ctx, passes, rule) ? "serverSendProbableLink" : outcome.note);
3432
3682
  const countRests = kind === "must" && failureRests && !ownNote;
3433
3683
  add2(`${kind}: ${rule.description}`, pass, evidence, message, countRests ? "warn" : outcome.severity, countRests ? "serverSendProbableLink" : note, scoped && (pass || failureRests));
3434
3684
  }
3435
- const containerRan = Boolean(runRecord && (runRecord.serverContainer || runRecord.testServerContainer) && !runRecord.serverContainer?.error);
3436
- builtInChecks(records, scenario, ctx, add2, containerRan);
3685
+ builtInChecks(records, scenario, ctx, add2, rejected);
3437
3686
  return results;
3438
3687
  }
3688
+ var REJECTED_MESSAGE = "cannot evaluate: the server container rejected most browser requests";
3689
+ var countNeedsMore = (count2, actual) => !countHolds(count2, actual) && (count2.op === ">=" || count2.op === ">" || count2.op === "=" && actual < count2.n);
3439
3690
  var isScoped = (rule) => Boolean(rule.before || rule.inEpoch || rule.after || rule.from || consentFields.some((f) => rule.filter.consent[f]));
3440
3691
  function ruleWindowStart(rule, ctx) {
3441
3692
  const label = rule.from ?? rule.after;
@@ -3583,17 +3834,17 @@ function evaluateRuleHits(rule, ctx) {
3583
3834
  message: (hits.length === 0 ? `Expected no matching hits${where2}, found none.` : `Expected no matching hits${where2}, ${found}.`) + (vacuous ? ` ${vacuous}` : "")
3584
3835
  };
3585
3836
  }
3586
- const count = rule.count ?? { op: ">=", n: 1 };
3587
- const pass = countHolds(count, hits.length);
3588
- const message = `Expected ${describeCount(count)} matching hits${where2}, ${found}.${vacuous ? ` ${vacuous}` : ""}`;
3837
+ const count2 = rule.count ?? { op: ">=", n: 1 };
3838
+ const pass = countHolds(count2, hits.length);
3839
+ const message = `Expected ${describeCount(count2)} matching hits${where2}, ${found}.${vacuous ? ` ${vacuous}` : ""}`;
3589
3840
  if (pass && rule.hashesMatch && hits.length > 0) {
3590
3841
  const check = checkHashes(hits, ctx);
3591
3842
  if (check.pass) return { pass: true, evidence: check.evidence, message: `${message} ${check.message}` };
3592
3843
  const matched = `${hits.length} hit${hits.length === 1 ? "" : "s"} matched ${describeSelector(rule.filter)}${where2}`;
3593
- const headline = check.headline ?? (countHolds(count, 0) ? UNMATCHED_HEADLINE : `Expected ${describeCount(count)} hits matching all conditions, found 0.`);
3844
+ const headline = check.headline ?? (countHolds(count2, 0) ? UNMATCHED_HEADLINE : `Expected ${describeCount(count2)} hits matching all conditions, found 0.`);
3594
3845
  return { pass: false, evidence: check.evidence, message: `${headline} ${matched}, but identity.hashesMatch failed: ${check.message}` };
3595
3846
  }
3596
- return { pass, evidence: ids, message };
3847
+ return { pass, evidence: ids, message, ...countNeedsMore(count2, hits.length) && { absent: true } };
3597
3848
  }
3598
3849
  var STUB_NO_COOKIES = "stub mode: stubbed endpoints set no cookies";
3599
3850
  function cookieSightings(matchers2, ctx) {
@@ -3635,13 +3886,13 @@ function storedState(sighting, ctx) {
3635
3886
  }
3636
3887
  var STORED_TEXT = { stored: "stored by the browser", notStored: "no later checkpoint has it", alreadySet: "the cookie was already set before this response" };
3637
3888
  function storageText(sightings, ctx) {
3638
- const byName = /* @__PURE__ */ new Map();
3889
+ const byName2 = /* @__PURE__ */ new Map();
3639
3890
  for (const sighting of sightings.filter((x) => x.source === "Set-Cookie")) {
3640
3891
  const state = storedState(sighting, ctx);
3641
- const previous = byName.get(sighting.name);
3642
- if (previous === void 0 || STORED_RANK[state] > STORED_RANK[previous]) byName.set(sighting.name, state);
3892
+ const previous = byName2.get(sighting.name);
3893
+ if (previous === void 0 || STORED_RANK[state] > STORED_RANK[previous]) byName2.set(sighting.name, state);
3643
3894
  }
3644
- const named = (want) => [...byName].filter(([, state]) => state === want).map(([name]) => guardFieldName(name)).sort();
3895
+ const named = (want) => [...byName2].filter(([, state]) => state === want).map(([name]) => guardFieldName(name)).sort();
3645
3896
  const stored = named("stored");
3646
3897
  const notStored = named("notStored");
3647
3898
  const alreadySet = named("alreadySet");
@@ -3710,8 +3961,8 @@ function evaluateCookieRule(rule, patterns, ctx) {
3710
3961
  const headerOnly = sources.length === 1 && sources[0] === "Set-Cookie";
3711
3962
  const requests = new Set(sightings.map((s) => s.evidence)).size;
3712
3963
  const storage = sightings.length ? storageText(sightings, ctx) : void 0;
3713
- const count = headerOnly ? `${requests} request${requests === 1 ? "" : "s"}` : `${total2} before narrowing`;
3714
- const found = sightings.length ? `found ${listNames(names)} from ${sources.join(" and ")} (${count})${storage ? `; ${storage.text}` : ""}${sources.some((s) => s !== "Set-Cookie") ? ". A checkpoint shows the cookie was present then, not when it was set" : ""}` : `found no matching cookie (${total2} before narrowing)`;
3964
+ const count2 = headerOnly ? `${requests} request${requests === 1 ? "" : "s"}` : `${total2} before narrowing`;
3965
+ const found = sightings.length ? `found ${listNames(names)} from ${sources.join(" and ")} (${count2})${storage ? `; ${storage.text}` : ""}${sources.some((s) => s !== "Set-Cookie") ? ". A checkpoint shows the cookie was present then, not when it was set" : ""}` : `found no matching cookie (${total2} before narrowing)`;
3715
3966
  const expected = rule.kind === "must" ? `Expected a matching cookie${where2}` : `Expected no matching cookie${where2}`;
3716
3967
  const stubbed = low && rule.kind === "mustNot" && ctx.networkMode === "stub";
3717
3968
  return {
@@ -3737,9 +3988,11 @@ function evaluatePushRuleIn(rule, ctx) {
3737
3988
  }
3738
3989
  function loaderReachesScope(loader, ctx, inScope, windowStartAt) {
3739
3990
  if (!loader) return true;
3991
+ const sameFrame2 = (r) => loader.frame && r.frame ? r.frame.n === loader.frame.n : r.frame?.main !== false;
3992
+ const aborted = (r) => r.outcome === "failed" && r.failure === "net::ERR_ABORTED";
3740
3993
  const navigations = [
3741
3994
  ...ctx.visitTimes,
3742
- ...[...ctx.requests.values()].filter((r) => r.resourceType === "document" && r.frame?.main !== false).map((r) => r.t)
3995
+ ...[...ctx.requests.values()].filter((r) => r.resourceType === "document" && !aborted(r) && sameFrame2(r)).map((r) => r.t)
3743
3996
  ];
3744
3997
  const start = Math.max(-Infinity, ...navigations.filter((t) => t <= loader.t));
3745
3998
  const end = Math.min(Infinity, ...navigations.filter((t) => t > loader.t));
@@ -3786,24 +4039,24 @@ function evaluateBodyRule(rule, body, selected, where2, total2, vacuous) {
3786
4039
  if (names2.length) matching.push({ hit, names: names2 });
3787
4040
  else if (hit.fieldsComplete === false) unreadable3.push(hit);
3788
4041
  }
3789
- const count = rule.kind === "must" ? rule.count ?? { op: ">=", n: 1 } : { op: "=", n: 0 };
3790
- const low = countHolds(count, matching.length);
3791
- const undecided = Array.from({ length: unreadable3.length }, (_, k) => countHolds(count, matching.length + k + 1)).some((holds) => holds !== low);
4042
+ const count2 = rule.kind === "must" ? rule.count ?? { op: ">=", n: 1 } : { op: "=", n: 0 };
4043
+ const low = countHolds(count2, matching.length);
4044
+ const undecided = Array.from({ length: unreadable3.length }, (_, k) => countHolds(count2, matching.length + k + 1)).some((holds) => holds !== low);
3792
4045
  if (undecided) return cannotEvaluate(unreadable3, where2);
3793
4046
  const names = [...new Set(matching.flatMap((m) => m.names))].sort();
3794
4047
  const evidence = matching.map((m) => m.hit.id);
3795
4048
  const found = matching.length ? `found ${matching.length} hit${matching.length === 1 ? "" : "s"} with body.has fields: ${listNames(names)}` : "found no hit with the body.has fields";
3796
- const expected = rule.kind === "must" ? `Expected ${describeCount(count)} hits with body.has fields${where2}` : `Expected no hit with body.has fields${where2}`;
4049
+ const expected = rule.kind === "must" ? `Expected ${describeCount(count2)} hits with body.has fields${where2}` : `Expected no hit with body.has fields${where2}`;
3797
4050
  const nested = matching.length ? [] : nestedNames(body.has.filter((n) => !n.includes("*")), selected);
3798
4051
  const nestedText = nested.length ? `; no top-level match; nested fields with this name: ${listNames(nested)}` : "";
3799
- return { pass: low, evidence, message: `${expected}, ${found} (${total2} before narrowing)${nestedText}.${tail}`, ...nested.length && { note: "nestedNameOnly" } };
4052
+ return { pass: low, evidence, ...rule.kind === "must" && countNeedsMore(count2, matching.length) && { absent: true }, message: `${expected}, ${found} (${total2} before narrowing)${nestedText}.${tail}`, ...nested.length && { note: "nestedNameOnly" } };
3800
4053
  }
3801
4054
  const only = body.only;
3802
4055
  const allowed = [...only, ...body.ignore ?? []].map(fieldGlob);
3803
4056
  if (rule.kind === "must") {
3804
- const count = rule.count ?? { op: ">=", n: 1 };
3805
- if (!countHolds(count, selected.length))
3806
- return { pass: false, evidence: selected.map((h) => h.id), message: `Expected ${describeCount(count)} matching hits${where2}, found ${selected.length}.${tail}` };
4057
+ const count2 = rule.count ?? { op: ">=", n: 1 };
4058
+ if (!countHolds(count2, selected.length))
4059
+ return { pass: false, evidence: selected.map((h) => h.id), message: `Expected ${describeCount(count2)} matching hits${where2}, found ${selected.length}.${tail}`, ...countNeedsMore(count2, selected.length) && { absent: true } };
3807
4060
  }
3808
4061
  const unreadable2 = [];
3809
4062
  const offenders = [];
@@ -4073,8 +4326,8 @@ function hashJudge(identity) {
4073
4326
  function capiMatchesIdentity(hit, field, identity) {
4074
4327
  const base2 = Object.hasOwn(META_CAPI_PARAM_NAMES, field) ? META_CAPI_PARAM_NAMES[field] : void 0;
4075
4328
  if (hit.vendor !== "meta-capi" || !identity || !base2) return null;
4076
- const judge2 = hashJudge(identity);
4077
- const verdicts2 = Object.entries(hit.params).filter(([name]) => metaCapiBaseParam(name) === base2).map(([name, value]) => judge2(hit.vendor, name, value)).filter((v) => v !== void 0);
4329
+ const judge3 = hashJudge(identity);
4330
+ const verdicts2 = Object.entries(hit.params).filter(([name]) => metaCapiBaseParam(name) === base2).map(([name, value]) => judge3(hit.vendor, name, value)).filter((v) => v !== void 0);
4078
4331
  return verdicts2.length === 0 ? null : verdicts2.every((v) => v === "match");
4079
4332
  }
4080
4333
  function checkHashes(hits, ctx) {
@@ -4087,7 +4340,7 @@ function checkHashes(hits, ctx) {
4087
4340
  message: "no run identity was given, so the hashes could not be checked."
4088
4341
  };
4089
4342
  }
4090
- const judge2 = hashJudge(identity);
4343
+ const judge3 = hashJudge(identity);
4091
4344
  const withHash = [];
4092
4345
  const wrong = [];
4093
4346
  const unhashed = [];
@@ -4109,7 +4362,7 @@ function checkHashes(hits, ctx) {
4109
4362
  for (const id of Object.keys(hit.ids)) if (id !== "hashedEmail" && id !== "hashedPhone") uncheckedFields.add(guardFieldName(id));
4110
4363
  }
4111
4364
  for (const [name, value] of Object.entries(hit.params)) {
4112
- const verdict = judge2(hit.vendor, name, value);
4365
+ const verdict = judge3(hit.vendor, name, value);
4113
4366
  if (!verdict) continue;
4114
4367
  const label = fieldLabel(identityParamName(hit.vendor, name));
4115
4368
  if (verdict === "plain") {
@@ -4215,7 +4468,7 @@ function countByHost(flags2, ctx) {
4215
4468
  return [...counts].map(([host, n]) => `${host} x${n}`).join(", ");
4216
4469
  }
4217
4470
  var DEFAULT_SEVERITY = { earlyIdentifiers: "warn", consentModeSetup: "warn", earlyIdentityPush: "warn", idHandover: "warn", serverContainerRejected: "warn" };
4218
- function builtInChecks(records, scenario, ctx, addResult, containerRan) {
4471
+ function builtInChecks(records, scenario, ctx, addResult, rejected) {
4219
4472
  const add2 = (name, pass, evidence2, message, note, timeJudged = false) => addResult(
4220
4473
  `builtin: ${name}`,
4221
4474
  pass,
@@ -4292,8 +4545,9 @@ function builtInChecks(records, scenario, ctx, addResult, containerRan) {
4292
4545
  problems.length === 0 ? "Expected no data that is not from the run identity, found none." : `Expected no data that is not from the run identity, found ${problems.length}: ${shown2}${more}.`
4293
4546
  );
4294
4547
  }
4295
- if (containerRan) {
4296
- const rejected = serverContainerRejected([...ctx.requests.values()], ctx.responses, scenario.options.serverHosts ?? []);
4548
+ const route = identifierRoute(records, ctx.grace, scenario.options.builtins?.identifierRoute, scenario.options.identifierRouteAllow);
4549
+ if (route) addResult("builtin: identifierRoute", route.pass, route.evidence, route.message, route.severity, route.note);
4550
+ if (rejected) {
4297
4551
  add2("serverContainerRejected", rejected.pass, rejected.evidence, rejected.message);
4298
4552
  }
4299
4553
  }
@@ -4722,8 +4976,73 @@ function findForeignData(requests, hits, identity, dataLayerEvents = []) {
4722
4976
  return out;
4723
4977
  }
4724
4978
 
4979
+ // packages/expect/src/state-table.ts
4980
+ var EVENT_NAME = /^[\w.:-]+(?: [\w.:-]+)*$/;
4981
+ var byName = (x, y) => x < y ? -1 : x > y ? 1 : 0;
4982
+ function guardName(name, isEvent = false) {
4983
+ if (isEvent && (name.length > 64 || !EVENT_NAME.test(name))) return OTHER_NAME;
4984
+ return guardFieldName(name) === name && !isValueSegment(name) ? name : OTHER_NAME;
4985
+ }
4986
+ function idNames(ids) {
4987
+ const names = [];
4988
+ for (const [name, value] of Object.entries(ids)) {
4989
+ if (value === true) names.push(guardName(name));
4990
+ else if (name === "hashes" && value && typeof value === "object") {
4991
+ for (const [hash, h] of Object.entries(value)) if (h.present) names.push(`hashes.${guardName(hash)}`);
4992
+ }
4993
+ }
4994
+ return names;
4995
+ }
4996
+ function countedHits(state, run) {
4997
+ if (state === "accept") return run.hits;
4998
+ const epochs = [...run.consentEpochs].sort((a, b) => a.startT - b.startT);
4999
+ const index = judgeIndex(run.hits, run.requests);
5000
+ const grace = run.run.graceWindowMs ?? DEFAULT_GRACE_MS;
5001
+ return run.hits.filter((hit) => {
5002
+ const t = judgedAt(hit, index);
5003
+ const label = t === void 0 ? void 0 : epochForHit(epochs, t, grace)?.label;
5004
+ return state === "withdraw" ? label === "withdrawn" : label !== "granted";
5005
+ });
5006
+ }
5007
+ function stateTable(records) {
5008
+ const tallies = /* @__PURE__ */ new Map();
5009
+ for (const state of CONSENT_STATES) {
5010
+ for (const run of records[state] ?? []) {
5011
+ for (const hit of countedHits(state, run)) {
5012
+ const row = tallies.get(hit.vendor) ?? tallies.set(hit.vendor, {}).get(hit.vendor);
5013
+ const tally = row[state] ??= { hits: 0, events: /* @__PURE__ */ new Set(), fields: /* @__PURE__ */ new Set(), ids: /* @__PURE__ */ new Set() };
5014
+ tally.hits++;
5015
+ if (hit.event) tally.events.add(guardName(hit.event, true));
5016
+ for (const f of hit.fields ?? []) tally.fields.add(guardName(f));
5017
+ for (const id of idNames(hit.ids)) tally.ids.add(id);
5018
+ }
5019
+ }
5020
+ }
5021
+ const vendors = [];
5022
+ const vendorsNotInAccept = {};
5023
+ for (const vendor of [...tallies.keys()].sort(byName)) {
5024
+ const row = tallies.get(vendor);
5025
+ const states = {};
5026
+ const notInAccept = {};
5027
+ for (const state of CONSENT_STATES) {
5028
+ if ((records[state] ?? []).length === 0) continue;
5029
+ const tally = row[state];
5030
+ states[state] = { hits: tally?.hits ?? 0, events: [...tally?.events ?? []].sort(byName), fields: [...tally?.fields ?? []].sort(byName), ids: [...tally?.ids ?? []].sort(byName) };
5031
+ if (state === "accept" || !tally || (records.accept ?? []).length === 0) continue;
5032
+ const accept = row.accept;
5033
+ notInAccept[state] = {
5034
+ events: [...tally.events].filter((e) => !accept?.events.has(e)).sort(byName),
5035
+ fields: [...tally.fields].filter((f) => !accept?.fields.has(f)).sort(byName)
5036
+ };
5037
+ if (!accept) (vendorsNotInAccept[state] ??= []).push(vendor);
5038
+ }
5039
+ vendors.push({ vendor, states, notInAccept });
5040
+ }
5041
+ return { vendors, vendorsNotInAccept };
5042
+ }
5043
+
4725
5044
  // packages/expect/src/event-map.ts
4726
- var EVENT_NAME = /^[A-Za-z0-9_.: -]{1,200}$/;
5045
+ var EVENT_NAME2 = /^[A-Za-z0-9_.: -]{1,200}$/;
4727
5046
  var PATH_NAME = /^[A-Za-z0-9_.()[\]*-]{1,200}$/;
4728
5047
  var ROOT = ".";
4729
5048
  var TOP_KEYS2 = /* @__PURE__ */ new Set(["events", "paths"]);
@@ -4802,8 +5121,8 @@ function parseEventMap(text2, file) {
4802
5121
  const eventsEntry = !isRecord(json.events) ? void 0 : top.findLast((e) => e.key === "events");
4803
5122
  (eventsEntry === void 0 ? [] : objectEntries(text2, eventsEntry.start)).forEach((e, i) => {
4804
5123
  const to = valueOf(text2, e);
4805
- if (!EVENT_NAME.test(e.key)) throw new Error(`${file}: "events" key ${i + 1} is not an event name.`);
4806
- if (typeof to !== "string" || !EVENT_NAME.test(to)) throw new Error(`${file}: "events" key ${i + 1} must map to an event name.`);
5124
+ if (!EVENT_NAME2.test(e.key)) throw new Error(`${file}: "events" key ${i + 1} is not an event name.`);
5125
+ if (typeof to !== "string" || !EVENT_NAME2.test(to)) throw new Error(`${file}: "events" key ${i + 1} must map to an event name.`);
4807
5126
  map.events[e.key] = to;
4808
5127
  });
4809
5128
  const paths = json.paths ?? {};
@@ -4812,7 +5131,7 @@ function parseEventMap(text2, file) {
4812
5131
  (pathsEntry === void 0 ? [] : objectEntries(text2, pathsEntry.start)).forEach((e, i) => {
4813
5132
  const at = `"paths" key ${i + 1}`;
4814
5133
  const renames = valueOf(text2, e);
4815
- if (!EVENT_NAME.test(e.key)) throw new Error(`${file}: ${at} is not an event name.`);
5134
+ if (!EVENT_NAME2.test(e.key)) throw new Error(`${file}: ${at} is not an event name.`);
4816
5135
  if (!isRecord(renames)) throw new Error(`${file}: ${at} must be an object.`);
4817
5136
  const out = /* @__PURE__ */ Object.create(null);
4818
5137
  const inner = objectEntries(text2, e.start);
@@ -5047,7 +5366,7 @@ function withoutEventName(n, other) {
5047
5366
  return { ...n, types };
5048
5367
  }
5049
5368
  function diffPushes(a, b, options = {}) {
5050
- const result = { eventsAdded: [], eventsRemoved: [], pathsAdded: [], pathsRemoved: [], typeChanges: [], moved: [], kindChanged: [], changed: false };
5369
+ const result = { eventsAdded: [], eventsRemoved: [], pathsAdded: [], pathsRemoved: [], pathsMoved: [], typeChanges: [], moved: [], kindChanged: [], changed: false };
5051
5370
  const mergeKinds = kindsMerged(a, b);
5052
5371
  const order = options.epochOrder ?? [];
5053
5372
  const na = pushNodes(pairNames(a, b, options.eventMap, { epochOrder: order, acrossFrames: options.acrossFrames, mergeKinds }), options.acrossFrames ?? false, mergeKinds);
@@ -5103,6 +5422,18 @@ function diffPushes(a, b, options = {}) {
5103
5422
  moveEpoch(g, match);
5104
5423
  }
5105
5424
  for (const f of fresh) if (!taken.has(f)) result.eventsAdded.push(nodeRef(f));
5425
+ const paired = /* @__PURE__ */ new Set();
5426
+ for (const r of result.pathsRemoved) {
5427
+ const to = result.pathsAdded.find(
5428
+ (n) => !paired.has(n) && n.event === r.event && n.kind === r.kind && n.frame === r.frame && n.path === r.path && n.types.join() === r.types.join() && neighbourEpochs(order, r.epoch, n.epoch)
5429
+ );
5430
+ if (!to) continue;
5431
+ paired.add(to);
5432
+ paired.add(r);
5433
+ result.pathsMoved.push({ event: r.event, ...r.renamedFrom === void 0 ? {} : { renamedFrom: r.renamedFrom }, path: r.path, types: r.types, frame: r.frame, ...r.kind === void 0 ? {} : { pushKind: r.kind }, from: r.epoch, to: to.epoch });
5434
+ }
5435
+ result.pathsRemoved = result.pathsRemoved.filter((r) => !paired.has(r));
5436
+ result.pathsAdded = result.pathsAdded.filter((n) => !paired.has(n));
5106
5437
  result.changed = result.eventsAdded.length + result.eventsRemoved.length + result.pathsAdded.length + result.pathsRemoved.length + result.typeChanges.length + result.kindChanged.length > 0;
5107
5438
  return result;
5108
5439
  }
@@ -5133,6 +5464,11 @@ function shapeFields(hit) {
5133
5464
  var keyId = (k) => JSON.stringify([k.epoch, k.vendor, k.event, k.page ?? null]);
5134
5465
  var groupId = (k) => JSON.stringify([k.vendor, k.event, k.page ?? null]);
5135
5466
  var tupleId = (t) => JSON.stringify([Object.entries(t.consent).sort(([x], [y]) => x < y ? -1 : x > y ? 1 : 0), t.ids]);
5467
+ function sameButGcdLetters(x, y) {
5468
+ const { gcd: gx = "", ...cx } = x.consent;
5469
+ const { gcd: gy = "", ...cy } = y.consent;
5470
+ return JSON.stringify([Object.entries(cx).sort(), x.ids]) === JSON.stringify([Object.entries(cy).sort(), y.ids]) && sameGcdState(gx, gy);
5471
+ }
5136
5472
  var total = (k) => (k?.tuples ?? []).reduce((n, t) => n + t.count, 0);
5137
5473
  function tupleCounts(k) {
5138
5474
  const out = /* @__PURE__ */ new Map();
@@ -5172,7 +5508,7 @@ function findMove(epochs, order) {
5172
5508
  return { from: from[0], to: to[0], count: Math.abs(d1) };
5173
5509
  }
5174
5510
  function diffShapes(a, b, options = {}) {
5175
- const result = { added: [], removed: [], countChanges: [], moved: [], drift: false };
5511
+ const result = { added: [], removed: [], countChanges: [], gcdLetters: [], moved: [], drift: false };
5176
5512
  const ia = new Map(a.map((k) => [keyId(k.key), k]));
5177
5513
  const ib = new Map(b.map((k) => [keyId(k.key), k]));
5178
5514
  const groups = /* @__PURE__ */ new Map();
@@ -5198,13 +5534,31 @@ function diffShapes(a, b, options = {}) {
5198
5534
  const key = (ka ?? kb).key;
5199
5535
  const ta = new Map((ka?.tuples ?? []).map((t) => [tupleId(t), t]));
5200
5536
  const tb = new Map((kb?.tuples ?? []).map((t) => [tupleId(t), t]));
5537
+ const lost = [...ta].map(([tid, t]) => ({ tid, t, left: tb.has(tid) ? Math.max(0, t.count - tb.get(tid).count) : t.count })).filter((l) => l.left > 0);
5201
5538
  for (const [tid, t] of tb) {
5202
5539
  const before = ta.get(tid);
5203
- if (!before) result.added.push({ key, consent: t.consent, ids: t.ids, wholeKey: !ka });
5204
- else if (before.count !== t.count) result.countChanges.push({ key, consent: t.consent, ids: t.ids, a: before.count, b: t.count });
5540
+ let need = before ? Math.max(0, t.count - before.count) : t.count;
5541
+ let first;
5542
+ while (need > 0) {
5543
+ const cand = lost.find((l) => l.left > 0 && l.tid !== tid && sameButGcdLetters(l.t, t));
5544
+ if (!cand) break;
5545
+ const n = Math.min(need, cand.left);
5546
+ need -= n;
5547
+ cand.left -= n;
5548
+ first ??= cand;
5549
+ result.gcdLetters.push({ key, consent: t.consent, ids: t.ids, a: cand.t.consent.gcd ?? "", b: t.consent.gcd ?? "" });
5550
+ }
5551
+ if (before) {
5552
+ if (before.count !== t.count) result.countChanges.push({ key, consent: t.consent, ids: t.ids, a: before.count, b: t.count });
5553
+ } else if (first && !tb.has(first.tid)) {
5554
+ first.left = 0;
5555
+ if (first.t.count !== t.count) result.countChanges.push({ key, consent: t.consent, ids: t.ids, a: first.t.count, b: t.count });
5556
+ } else if (need > 0) {
5557
+ result.added.push({ key, consent: t.consent, ids: t.ids, wholeKey: !ka });
5558
+ }
5205
5559
  }
5206
- for (const [tid, t] of ta) {
5207
- if (!tb.has(tid)) result.removed.push({ key, consent: t.consent, ids: t.ids, wholeKey: !kb });
5560
+ for (const l of lost) {
5561
+ if (l.left > 0 && !tb.has(l.tid)) result.removed.push({ key, consent: l.t.consent, ids: l.t.ids, wholeKey: !kb });
5208
5562
  }
5209
5563
  }
5210
5564
  result.drift = result.added.length > 0 || result.removed.length > 0;
@@ -5304,10 +5658,10 @@ function flagCounts(run) {
5304
5658
  for (const flag2 of run.flags) {
5305
5659
  const host = flag2.recordIds.map((id) => requestHosts.get(id) ?? hitHosts.get(id)).find((h) => h) ?? "";
5306
5660
  const key = JSON.stringify([host, flag2.kind]);
5307
- const count = counts.get(key) ?? { n: 0, allowed: true };
5308
- count.n += 1;
5309
- count.allowed &&= allowedIds.has(flag2.id);
5310
- counts.set(key, count);
5661
+ const count2 = counts.get(key) ?? { n: 0, allowed: true };
5662
+ count2.n += 1;
5663
+ count2.allowed &&= allowedIds.has(flag2.id);
5664
+ counts.set(key, count2);
5311
5665
  }
5312
5666
  return counts;
5313
5667
  }
@@ -6900,7 +7254,7 @@ function buildDataLayerNotHookedFlag(input) {
6900
7254
  const listed = names.slice(0, MAX_LISTED_NAMES).join(", ");
6901
7255
  const rest = names.length - MAX_LISTED_NAMES;
6902
7256
  const shown2 = rest > 0 ? `${listed} and ${rest} more` : listed;
6903
- const plural3 = names.length > 1;
7257
+ const plural4 = names.length > 1;
6904
7258
  const advice = misses.every((m) => untrapped.has(m.name) && input.hooked.includes(m.name)) ? "The page defines them in a way the hook cannot trap." : "Add them to options.dataLayerNames.";
6905
7259
  return {
6906
7260
  type: "flag",
@@ -6908,7 +7262,7 @@ function buildDataLayerNotHookedFlag(input) {
6908
7262
  runId: input.runId,
6909
7263
  kind: "dataLayerNotHooked",
6910
7264
  recordIds: misses.map((m) => m.id),
6911
- detail: plural3 ? `Google loaders name the data layers ${shown2}, which are not hooked, so pushes to them are not recorded. ${advice}` : `A Google loader names the data layer ${shown2}, which is not hooked, so pushes to it are not recorded. ${advice.replace("them", "it")}`
7265
+ detail: plural4 ? `Google loaders name the data layers ${shown2}, which are not hooked, so pushes to them are not recorded. ${advice}` : `A Google loader names the data layer ${shown2}, which is not hooked, so pushes to it are not recorded. ${advice.replace("them", "it")}`
6912
7266
  };
6913
7267
  }
6914
7268
  function buildDataLayerReassignedFlags(input) {
@@ -7003,15 +7357,204 @@ function parseTagReport(payload, side, ctx) {
7003
7357
  return { ok: true, report, version };
7004
7358
  }
7005
7359
 
7360
+ // packages/recorder/src/canary-routes.ts
7361
+ import { getDomain as getDomain3 } from "tldts";
7362
+ var BODY_FIELD = "(body)";
7363
+ var PATH_FIELD = "(path)";
7364
+ var FRAGMENT_FIELD = "(fragment)";
7365
+ var MAX_DEPTH4 = 2;
7366
+ var COMPRESSED = /^(?:gzip|br|deflate|zstd|compress)\b/i;
7367
+ var BINARY = /[\u0000-\u0008\u000e-\u001f\u007f-\u009f]/;
7368
+ function transformForms(value) {
7369
+ const buffer = Buffer.from(value);
7370
+ return [
7371
+ [value, "plain"],
7372
+ [encodeURIComponent(value), "url"],
7373
+ [buffer.toString("base64"), "base64"],
7374
+ [buffer.toString("base64url"), "base64url"],
7375
+ ...[...fieldHashes(value)].map((hash) => [hash, "sha256"])
7376
+ ];
7377
+ }
7378
+ function parse2(url) {
7379
+ try {
7380
+ return new URL(url);
7381
+ } catch {
7382
+ return void 0;
7383
+ }
7384
+ }
7385
+ function decodeOrSame(text2) {
7386
+ try {
7387
+ return decodeURIComponent(text2);
7388
+ } catch {
7389
+ return text2;
7390
+ }
7391
+ }
7392
+ function isFirstParty(host, siteHost, firstPartyHosts) {
7393
+ if (host === siteHost || hostMatches(host, firstPartyHosts)) return true;
7394
+ const domain = getDomain3(siteHost, { allowPrivateDomains: true });
7395
+ return domain !== null && getDomain3(host, { allowPrivateDomains: true }) === domain;
7396
+ }
7397
+ function isBinaryBody2(req) {
7398
+ const encoding = Object.entries(req.headers).find(([name]) => name.toLowerCase() === "content-encoding")?.[1];
7399
+ if (encoding !== void 0 && COMPRESSED.test(encoding.trim())) return true;
7400
+ return req.postData !== null && BINARY.test(req.postData);
7401
+ }
7402
+ function pairsOf(text2) {
7403
+ const url = /^https?:\/\//i.test(text2) ? parse2(text2) : void 0;
7404
+ if (url) {
7405
+ const hash = url.hash.slice(1);
7406
+ return [...url.searchParams, ...hash.includes("=") ? new URLSearchParams(hash) : []];
7407
+ }
7408
+ if (!text2.includes("=")) return [];
7409
+ return text2.split(/[&;]\s*/).flatMap((pair) => {
7410
+ const eq = pair.indexOf("=");
7411
+ return eq < 0 ? [] : [[pair.slice(0, eq), pair.slice(eq + 1)]];
7412
+ });
7413
+ }
7414
+ function scan2(text2, pool, transforms, depth = 0) {
7415
+ const found = /* @__PURE__ */ new Map();
7416
+ const layers = readings(text2);
7417
+ const name = pool.match(text2);
7418
+ if (name !== void 0) {
7419
+ const read = layers.find((layer) => transforms.has(layer));
7420
+ found.set(name, { name, transform: read === void 0 ? "other" : transforms.get(read) });
7421
+ }
7422
+ if (depth < MAX_DEPTH4) {
7423
+ for (const layer of layers) {
7424
+ for (const [, value] of pairsOf(layer)) {
7425
+ for (const inner of scan2(value, pool, transforms, depth + 1)) if (!found.has(inner.name)) found.set(inner.name, inner);
7426
+ }
7427
+ }
7428
+ }
7429
+ return [...found.values()];
7430
+ }
7431
+ function occurrencesOf(req, url, hits, searchBody, pool, transforms) {
7432
+ const out = [];
7433
+ const add2 = (raw, value, field = pool.match(raw) === void 0 ? guardFieldName(raw) : OTHER_NAME) => {
7434
+ for (const { name, transform } of scan2(value, pool, transforms)) {
7435
+ if (!out.some((o) => o.name === name && o.transform === transform && o.field === field && o.value === value)) out.push({ name, transform, raw, field, value });
7436
+ }
7437
+ };
7438
+ for (const [key, value] of url.searchParams) {
7439
+ add2(key, value);
7440
+ add2(key, key, OTHER_NAME);
7441
+ }
7442
+ for (const segment of url.pathname.split("/")) if (segment) add2(PATH_FIELD, decodeOrSame(segment), PATH_FIELD);
7443
+ const hash = url.hash.slice(1);
7444
+ if (hash.includes("=")) {
7445
+ for (const [key, value] of new URLSearchParams(hash)) {
7446
+ add2(key, value);
7447
+ add2(key, key, OTHER_NAME);
7448
+ }
7449
+ } else if (hash) add2(FRAGMENT_FIELD, hash, FRAGMENT_FIELD);
7450
+ if (searchBody && req.postData) {
7451
+ for (const { name, value } of bodyEntries(req).entries) {
7452
+ add2(name, value);
7453
+ add2(name, name, OTHER_NAME);
7454
+ }
7455
+ for (const [form, name] of pool.forms) {
7456
+ if (req.postData.includes(form) && !out.some((o) => o.name === name)) out.push({ name, transform: transforms.get(form) ?? "other", raw: BODY_FIELD, field: BODY_FIELD, value: form });
7457
+ }
7458
+ }
7459
+ for (const hit of hits) {
7460
+ for (const [key, value] of Object.entries(hit.params)) {
7461
+ add2(key, value);
7462
+ add2(key, key, OTHER_NAME);
7463
+ }
7464
+ }
7465
+ return out;
7466
+ }
7467
+ function pageFieldsOf(vendor) {
7468
+ const fields2 = PAGE_FIELDS[vendor];
7469
+ return fields2 ? [...fields2.page, ...fields2.referrer] : [];
7470
+ }
7471
+ function routeKind(occurrences, pageFields, pages, identity) {
7472
+ if (identity) return { kind: "direct", chosen: occurrences[0] };
7473
+ const own = occurrences.find((o) => o.raw === o.name);
7474
+ if (own) return { kind: "direct", chosen: own };
7475
+ const isPage = (o) => pageFields.has(o.raw) || pages.has(o.value);
7476
+ const other = occurrences.find((o) => !isPage(o));
7477
+ return other ? { kind: "unknown", chosen: other } : { kind: "pageUrl", chosen: occurrences[0] };
7478
+ }
7479
+ function firstSighting(checkpoints, canary, t) {
7480
+ let best;
7481
+ for (const checkpoint of checkpoints) {
7482
+ if (checkpoint.t === void 0 || checkpoint.t >= t || best && best.checkpoint.t <= checkpoint.t) continue;
7483
+ const cookie = checkpoint.cookies.find((c) => c.firstParty && c.canary === canary);
7484
+ if (cookie) best = { checkpoint, cookie };
7485
+ }
7486
+ return best;
7487
+ }
7488
+ function linkedHit(own, byId2, pool) {
7489
+ const via = (own.find((h) => h.via?.confidence === "exact") ?? own.find((h) => h.via))?.via;
7490
+ const browser = via && byId2.get(via.hitId);
7491
+ if (!via || !browser) return void 0;
7492
+ return { hop: { kind: "hit", hitId: via.hitId, confidence: via.confidence }, label: browser.event === null ? browser.vendor : `${browser.vendor} ${pool.match(browser.event) === void 0 ? guardFieldName(browser.event) : OTHER_NAME}` };
7493
+ }
7494
+ var plural2 = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
7495
+ function buildCanaryFlags(input) {
7496
+ const { runId, siteUrl, firstPartyHosts = [], serverHosts = [], requests, hits, checkpoints = [], canaries, identity = null } = input;
7497
+ if (canaries.length === 0) return [];
7498
+ const pool = input.pool ?? canaryPool(canaries, identity);
7499
+ const transforms = /* @__PURE__ */ new Map();
7500
+ const values = [...canaries.map((c) => c.value), ...identity ? [identity.email, identity.phone] : []];
7501
+ for (const value of values) for (const [form, transform] of transformForms(value)) if (!transforms.has(form)) transforms.set(form, transform);
7502
+ const canaryNames = new Set(canaries.map((c) => c.name));
7503
+ const siteHost = parse2(siteUrl)?.hostname ?? "";
7504
+ const hitsByRequest = /* @__PURE__ */ new Map();
7505
+ const hitsById = new Map(hits.map((h) => [h.id, h]));
7506
+ for (const hit of hits) hitsByRequest.set(hit.requestId, [...hitsByRequest.get(hit.requestId) ?? [], hit]);
7507
+ const flags2 = [];
7508
+ const skipped = { binary: /* @__PURE__ */ new Set(), cut: /* @__PURE__ */ new Set(), netLog: /* @__PURE__ */ new Set() };
7509
+ let searched = 0;
7510
+ for (const req of requests) {
7511
+ const url = parse2(req.url);
7512
+ if (!url || !/^https?:$/.test(url.protocol)) continue;
7513
+ if (isFirstParty(url.hostname, siteHost, firstPartyHosts) || isServerHostUrl(req.url, serverHosts)) continue;
7514
+ searched += 1;
7515
+ const binary = isBinaryBody2(req);
7516
+ if (binary) skipped.binary.add(req.id);
7517
+ else if (req.postData !== null && req.postData.length >= MAX_POST_DATA) skipped.cut.add(req.id);
7518
+ if (req.captured === "netlog" && req.postData === null && req.method !== "GET" && req.method !== "HEAD") skipped.netLog.add(req.id);
7519
+ const own = hitsByRequest.get(req.id) ?? [];
7520
+ const occurrences = occurrencesOf(req, url, own, !binary, pool, transforms);
7521
+ const vendor = own[0]?.vendor ?? "unknown";
7522
+ const pageFields = new Set(own.flatMap((h) => pageFieldsOf(h.vendor)));
7523
+ const pages = new Set(own.flatMap((h) => h.page ? [h.page] : []));
7524
+ for (const name of new Set(occurrences.map((o) => o.name))) {
7525
+ const { kind, chosen } = routeKind(occurrences.filter((o) => o.name === name), pageFields, pages, !canaryNames.has(name));
7526
+ const source = canaryNames.has(name) ? { source: "urlParam", name } : { source: "identity", name };
7527
+ const seen = kind === "unknown" && source.source === "urlParam" ? firstSighting(checkpoints, name, req.t) : void 0;
7528
+ const cookie = seen ? [{ kind: "cookie", name: pool.match(seen.cookie.name) === void 0 ? guardFieldName(seen.cookie.name) : OTHER_NAME, checkpointId: seen.checkpoint.id }] : [];
7529
+ const linked = req.captured === "serverContainer" ? linkedHit(own, hitsById, pool) : void 0;
7530
+ const hops = [...cookie, ...linked ? [linked.hop] : []];
7531
+ const route = { kind: seen ? "cookie" : kind, source, sink: { requestId: req.id, host: url.hostname, vendor, field: chosen.field, transform: chosen.transform }, hops };
7532
+ const from = source.source === "urlParam" ? `url param ${name}` : `identity ${name}`;
7533
+ const viaCookie = seen ? ` -> cookie ${cookie[0].name} (checkpoint ${seen.checkpoint.label})` : "";
7534
+ const tail = linked ? ` -> hit (${linked.label}) -> server call (${vendor}, ${chosen.field}, ${chosen.transform}), link ${linked.hop.confidence}` : ` -> request to ${url.hostname}, param ${chosen.field}, ${chosen.transform}`;
7535
+ flags2.push({ type: "flag", id: newId("flag"), runId, kind: "identifierRoute", recordIds: [req.id], detail: `${from}${viaCookie}${tail}`, route });
7536
+ }
7537
+ }
7538
+ const ids = [.../* @__PURE__ */ new Set([...skipped.binary, ...skipped.cut, ...skipped.netLog])];
7539
+ const what = `${plural2(canaries.length, "canary value")}${identity ? " and the identity email and phone" : ""}`;
7540
+ const detail = `Searched ${plural2(searched, "request")} to non-first-party hosts for ${what} as plain text, URL-encoded, base64, base64url and SHA-256 (hex, base64, base64url), and with the GCL. and fb.1. cookie prefixes. Searched: URL, body and decoded fields. Not searched: headers (Referer and Cookie). Skipped: compressed or binary body ${skipped.binary.size}, body cut at 64 KiB ${skipped.cut.size}, net-log request with no body ${skipped.netLog.size}.`;
7541
+ flags2.push({ type: "flag", id: newId("flag"), runId, kind: "canarySearch", recordIds: ids, detail });
7542
+ return flags2;
7543
+ }
7544
+
7006
7545
  // packages/recorder/src/redact.ts
7007
7546
  var REDACTED_HEADERS = /* @__PURE__ */ new Set(["authorization", "proxy-authorization", "cookie", "set-cookie", "access-token", "x-api-key"]);
7008
7547
  var REDACTED = "[redacted]";
7548
+ function secretHeaderNamesIn(headers) {
7549
+ return Object.keys(headers).map((k) => k.toLowerCase()).filter((k) => REDACTED_HEADERS.has(k));
7550
+ }
7009
7551
  function redactHeaders(headers) {
7010
7552
  return Object.fromEntries(
7011
7553
  Object.entries(headers).map(([k, v]) => [k, REDACTED_HEADERS.has(k.toLowerCase()) ? REDACTED : v])
7012
7554
  );
7013
7555
  }
7014
7556
  var SECRET_VALUE_NAMES = ["access_token", "appsecret_proof"];
7557
+ var SECRET_NAME_SET = new Set(SECRET_VALUE_NAMES);
7015
7558
  var NAMES = SECRET_VALUE_NAMES.join("|");
7016
7559
  var IN_URL = new RegExp(`([?&;])(${NAMES})=[^&#]*`, "gi");
7017
7560
  var IN_FORM = new RegExp(`(^|&)(${NAMES})=[^&]*`, "gi");
@@ -7022,6 +7565,23 @@ function redactSecretsInUrl(url) {
7022
7565
  function redactSecretsInBody(body) {
7023
7566
  return body.replace(IN_JSON, `$1"${REDACTED}"`).replace(IN_FORM, `$1$2=${REDACTED}`);
7024
7567
  }
7568
+ function collectNames(scan4) {
7569
+ const found = /* @__PURE__ */ new Set();
7570
+ scan4((_, ...groups) => {
7571
+ for (const g of groups) if (typeof g === "string" && SECRET_NAME_SET.has(g.toLowerCase())) found.add(g.toLowerCase());
7572
+ return "";
7573
+ });
7574
+ return [...found];
7575
+ }
7576
+ function secretNamesInUrl(url) {
7577
+ return collectNames((note) => url.replace(IN_URL, note));
7578
+ }
7579
+ function secretNamesInBody(body) {
7580
+ return collectNames((note) => {
7581
+ const afterJson = body.replace(IN_JSON, (m) => note(m, m.slice(1, m.indexOf('"', 1))) + `"${REDACTED}"`);
7582
+ afterJson.replace(IN_FORM, note);
7583
+ });
7584
+ }
7025
7585
 
7026
7586
  // packages/recorder/src/netlog-dir.ts
7027
7587
  import { rmSync } from "node:fs";
@@ -7141,9 +7701,9 @@ function mergeNetLog(entries, recorded, steps, trackers, runId, navigations = []
7141
7701
  for (const entry of entries) {
7142
7702
  if (entry.method === "OPTIONS") continue;
7143
7703
  const key = `${entry.method} ${entry.url}`;
7144
- const count = seen.get(key) ?? 0;
7145
- if (count > 0) {
7146
- seen.set(key, count - 1);
7704
+ const count2 = seen.get(key) ?? 0;
7705
+ if (count2 > 0) {
7706
+ seen.set(key, count2 - 1);
7147
7707
  continue;
7148
7708
  }
7149
7709
  const candidate = { method: entry.method, url: entry.url, resourceType: "other", postData: null };
@@ -7559,7 +8119,7 @@ import { isAbsolute } from "node:path";
7559
8119
 
7560
8120
  // packages/recorder/src/gtm-scrub.ts
7561
8121
  var REDACTED2 = "[redacted]";
7562
- var MAX_DEPTH4 = 8;
8122
+ var MAX_DEPTH5 = 8;
7563
8123
  var BASE64_TOKEN2 = /[A-Za-z0-9+/_-]{8,}={0,2}/g;
7564
8124
  var QUERY_LIKE = /^[\w.[\]-]+=[^&\s]*(?:&[\w.[\]-]+=[^&\s]*)*$/;
7565
8125
  function decodeBase64Text2(value) {
@@ -7583,7 +8143,7 @@ function queryValues(text2) {
7583
8143
  function containsSecret(text2, secret, depth = 0) {
7584
8144
  if (text2.length < secret.length) return false;
7585
8145
  if (text2.includes(secret)) return true;
7586
- if (depth >= MAX_DEPTH4) return false;
8146
+ if (depth >= MAX_DEPTH5) return false;
7587
8147
  const next = depth + 1;
7588
8148
  const decoded = urlDecode(text2);
7589
8149
  if (decoded !== text2 && containsSecret(decoded, secret, next)) return true;
@@ -8170,6 +8730,10 @@ function flattenHeaders(headers) {
8170
8730
  }
8171
8731
  function captureServerContainerCall(call, context) {
8172
8732
  const text2 = call.body.length === 0 ? null : call.body.toString("utf8");
8733
+ const headers = flattenHeaders(call.headers);
8734
+ const secretsRedacted = [
8735
+ .../* @__PURE__ */ new Set([...secretNamesInUrl(call.url), ...text2 === null ? [] : secretNamesInBody(text2), ...secretHeaderNamesIn(headers)])
8736
+ ].sort();
8173
8737
  return {
8174
8738
  type: "request",
8175
8739
  id: newId("request"),
@@ -8181,10 +8745,11 @@ function captureServerContainerCall(call, context) {
8181
8745
  resourceType: "fetch",
8182
8746
  frameUrl: null,
8183
8747
  initiator: "serverContainer",
8184
- headers: redactHeaders(flattenHeaders(call.headers)),
8748
+ headers: redactHeaders(headers),
8185
8749
  postData: text2 === null ? null : redactSecretsInBody(text2).slice(0, MAX_POST_DATA),
8186
8750
  outcome: "stubbed",
8187
- captured: "serverContainer"
8751
+ captured: "serverContainer",
8752
+ ...secretsRedacted.length > 0 && { secretsRedacted }
8188
8753
  };
8189
8754
  }
8190
8755
  function serverContainerAnswer(request) {
@@ -8332,6 +8897,13 @@ function clientIdsOf(request) {
8332
8897
  addQuery(new URL(request.url).searchParams);
8333
8898
  } catch {
8334
8899
  }
8900
+ const unwrapped = unwrapStapeLoader(request);
8901
+ if (unwrapped) {
8902
+ try {
8903
+ addQuery(new URL(unwrapped.url).searchParams);
8904
+ } catch {
8905
+ }
8906
+ }
8335
8907
  const body = request.postData;
8336
8908
  if (body) {
8337
8909
  try {
@@ -8378,9 +8950,10 @@ function linkServerHits({ hits, requests, serverHosts, identity, inFlight }) {
8378
8950
  };
8379
8951
  });
8380
8952
  const hitRequestIds = new Set(hits.map((h) => h.requestId));
8953
+ const sentAtOf = (requestId, t) => inFlight?.get(requestId)?.sentAt ?? t;
8381
8954
  const hasConcurrentRequest = (only, from, to, callClientIds) => requests.some((r) => {
8382
8955
  if (r.captured === "serverContainer" || r.id === only.hit.requestId || r.initiator === "unload" || !isServerContainerRequest(r, serverHosts)) return false;
8383
- const sentAt = inFlight?.get(r.id)?.sentAt ?? r.t;
8956
+ const sentAt = sentAtOf(r.id, r.t);
8384
8957
  if (sentAt < from || sentAt > to) return false;
8385
8958
  if (!hitRequestIds.has(r.id)) return true;
8386
8959
  return [...clientIdsOf(r)].some((id) => callClientIds.has(id));
@@ -8389,13 +8962,16 @@ function linkServerHits({ hits, requests, serverHosts, identity, inFlight }) {
8389
8962
  const browser = facts.filter((f) => !isServer(f));
8390
8963
  return facts.map((f) => {
8391
8964
  if (!isServer(f)) return f.hit;
8392
- const exact = f.eventId === void 0 ? [] : browser.filter((b) => b.eventId === f.eventId && b.hit.event === f.hit.event);
8965
+ const callAt = f.request?.t;
8966
+ const exact = f.eventId === void 0 ? [] : browser.filter((b) => {
8967
+ if (b.eventId !== f.eventId || b.hit.event !== f.hit.event) return false;
8968
+ return callAt === void 0 || sentAtOf(b.hit.requestId, b.hit.t) <= callAt;
8969
+ });
8393
8970
  if (exact.length === 1) return { ...f.hit, via: { hitId: exact[0].hit.id, by: "eventId", confidence: "exact" } };
8394
8971
  const eventIdMiss = f.eventId === void 0 || f.hit.event === null ? "none" : exact.length === 0 ? "noMatch" : "several";
8395
- const callAt = f.request?.t;
8396
8972
  const sameKey = callAt === void 0 || f.hit.event === null ? [] : browser.filter((b) => {
8397
8973
  if (!b.onServerHost || b.hit.event !== f.hit.event) return false;
8398
- const sentAt = inFlight?.get(b.hit.requestId)?.sentAt ?? b.hit.t;
8974
+ const sentAt = sentAtOf(b.hit.requestId, b.hit.t);
8399
8975
  if (sentAt > callAt) return false;
8400
8976
  for (const id of f.clientIds) if (b.clientIds.has(id)) return true;
8401
8977
  return false;
@@ -8419,6 +8995,28 @@ function linkServerHits({ hits, requests, serverHosts, identity, inFlight }) {
8419
8995
  });
8420
8996
  }
8421
8997
 
8998
+ // packages/recorder/src/server-container/loader-path.ts
8999
+ var SERVER_CLIENT_PATHS = /* @__PURE__ */ new Set(["/g/collect", "/data"]);
9000
+ var STAPE_LOADER_LOSES = "what Stape's hosting layer does with a loader request: its own headers, Cookie Keeper and any change to the path or body";
9001
+ function containerPathFor(url) {
9002
+ let live;
9003
+ try {
9004
+ live = new URL(url);
9005
+ } catch {
9006
+ return { pathAndQuery: url, unwrapped: false };
9007
+ }
9008
+ const unchanged = { pathAndQuery: `${live.pathname}${live.search}`, unwrapped: false };
9009
+ const real = unwrapStapeLoader({ url });
9010
+ if (!real) return unchanged;
9011
+ try {
9012
+ const target = new URL(real.url);
9013
+ if (!SERVER_CLIENT_PATHS.has(target.pathname)) return unchanged;
9014
+ return { pathAndQuery: `${target.pathname}${target.search}`, unwrapped: true };
9015
+ } catch {
9016
+ return unchanged;
9017
+ }
9018
+ }
9019
+
8422
9020
  // packages/recorder/src/unload.ts
8423
9021
  var UNLOAD_BINDING = "__tagreeveUnloadSend";
8424
9022
  var UNLOAD_FLUSH = "__tagreeveFlushUnload";
@@ -8586,6 +9184,7 @@ var Recorder = class _Recorder {
8586
9184
  routed = /* @__PURE__ */ new Set();
8587
9185
  /** Memory only: never a record field. */
8588
9186
  containerFlights = /* @__PURE__ */ new Map();
9187
+ loaderUnwrapped = 0;
8589
9188
  handedToChromium = /* @__PURE__ */ new Set();
8590
9189
  redirectHeaderWithoutRedirect = /* @__PURE__ */ new Set();
8591
9190
  selfRecorded = /* @__PURE__ */ new WeakSet();
@@ -9008,7 +9607,6 @@ var Recorder = class _Recorder {
9008
9607
  /** Answers a non-load request to a `serverHosts` host with the local container's response. It never reaches the remote host. */
9009
9608
  async routeToContainer(route, record, origin) {
9010
9609
  const original = route.request();
9011
- const live = new URL(original.url());
9012
9610
  const { host: _host, ...headers } = await original.allHeaders();
9013
9611
  void _host;
9014
9612
  record.outcome = "stubbed";
@@ -9017,7 +9615,9 @@ var Recorder = class _Recorder {
9017
9615
  try {
9018
9616
  client = await playwrightRequest.newContext();
9019
9617
  const sentAt = nodeNow();
9020
- const response = await client.fetch(`${origin}${live.pathname}${live.search}`, {
9618
+ const { pathAndQuery, unwrapped } = containerPathFor(original.url());
9619
+ if (unwrapped) this.loaderUnwrapped += 1;
9620
+ const response = await client.fetch(`${origin}${pathAndQuery}`, {
9021
9621
  method: original.method(),
9022
9622
  headers,
9023
9623
  data: original.postDataBuffer() ?? void 0,
@@ -9107,7 +9707,8 @@ var Recorder = class _Recorder {
9107
9707
  passThrough: counts?.passThrough ?? { serverjs: 0, config: 0, destination: 0 },
9108
9708
  refused: counts?.refused ?? 0,
9109
9709
  unlinked: hits.filter((h) => fromContainer.has(h.requestId) && h.via === void 0).length,
9110
- ...failure ? { error: failure.errorClass } : {}
9710
+ ...failure ? { error: failure.errorClass } : {},
9711
+ ...this.loaderUnwrapped > 0 ? { loaderUnwrapped: { loader: "stape", requests: this.loaderUnwrapped, loses: STAPE_LOADER_LOSES } } : {}
9111
9712
  };
9112
9713
  if (failure) {
9113
9714
  flags2.push({ type: "flag", id: newId("flag"), runId: this.runId, kind: "serverContainerFailed", recordIds: [], detail: `The server container did not run: ${failure.errorClass}.` });
@@ -9280,13 +9881,16 @@ var Recorder = class _Recorder {
9280
9881
  }
9281
9882
  async checkpoint(label, step) {
9282
9883
  const host = new URL(this.options.site).hostname;
9884
+ const pool = this.options.canaries?.length ? canaryPool(this.options.canaries, this.run.identity) : void 0;
9283
9885
  const cookies = (await this.context.cookies()).map((c) => {
9284
9886
  const domain = c.domain.replace(/^\./, "");
9887
+ const canary = pool?.match(c.value);
9285
9888
  return {
9286
9889
  name: c.name,
9287
9890
  domain: c.domain,
9288
9891
  expires: c.expires > 0 ? c.expires * 1e3 : null,
9289
- firstParty: host === domain || host.endsWith(`.${domain}`)
9892
+ firstParty: isFirstParty(domain, host, this.options.firstPartyHosts ?? []),
9893
+ ...canary === void 0 ? {} : { canary }
9290
9894
  };
9291
9895
  });
9292
9896
  const checkpoint = {
@@ -9417,6 +10021,9 @@ var Recorder = class _Recorder {
9417
10021
  handedToChromium: this.handedToChromium,
9418
10022
  redirectHeaderWithoutRedirect: this.redirectHeaderWithoutRedirect
9419
10023
  });
10024
+ if (this.options.canaries?.length) {
10025
+ flags2.push(...buildCanaryFlags({ runId: this.runId, siteUrl: this.options.site, firstPartyHosts: this.options.firstPartyHosts, serverHosts: this.options.serverHosts, requests, hits, checkpoints: this.checkpoints, canaries: this.options.canaries, identity: this.run.identity }));
10026
+ }
9420
10027
  if (!this.netLogPath) {
9421
10028
  const embedded = this.dataLayerEvents.filter((e) => !e.frame?.main);
9422
10029
  flags2.push(...buildUnloadGapFlags({ runId: this.runId, networkMode: this.options.networkMode, events: embedded, hits, navigations: this.navigations, runEnd: closeStartedAt, eventFrames: this.eventFrames, requestFrames: new Map(requests.map((r) => [r.id, { id: this.requestFrameIds.get(r.id) ?? null, url: r.frameUrl }])), ignore: this.options.unloadGapIgnore }));
@@ -9859,8 +10466,8 @@ async function fillVerified(element, field, cardHost, value, deadline, typed) {
9859
10466
  const frame = await readable(frameStillServed(element, cardHost, field));
9860
10467
  const checkedUrl = frame.url();
9861
10468
  const inputs = frame.locator(field.input).filter({ visible: true });
9862
- const count = await readable(inputs.count());
9863
- if (count === 1) {
10469
+ const count2 = await readable(inputs.count());
10470
+ if (count2 === 1) {
9864
10471
  let handle;
9865
10472
  try {
9866
10473
  handle = await inputs.elementHandle({ timeout: tryMs() });
@@ -9886,11 +10493,11 @@ async function fillVerified(element, field, cardHost, value, deadline, typed) {
9886
10493
  }
9887
10494
  }
9888
10495
  if (Date.now() >= deadline) {
9889
- const unreadable2 = new OwnReason(`${count} visible inputs match in ${pathOf2(checkedUrl)}: inputs not readable`);
10496
+ const unreadable2 = new OwnReason(`${count2} visible inputs match in ${pathOf2(checkedUrl)}: inputs not readable`);
9890
10497
  const settle = async () => {
9891
10498
  const current = await frameStillServed(element, cardHost, field).catch(() => void 0);
9892
10499
  if (!current || current.url() !== checkedUrl) throw new OwnReason(GONE_FRAME);
9893
- const reason = await countReason(current, pathOf2(checkedUrl), count, typed);
10500
+ const reason = await countReason(current, pathOf2(checkedUrl), count2, typed);
9894
10501
  if ((await frameStillServed(element, cardHost, field)).url() !== checkedUrl) throw new OwnReason(GONE_FRAME);
9895
10502
  throw new OwnReason(reason);
9896
10503
  };
@@ -9899,7 +10506,7 @@ async function fillVerified(element, field, cardHost, value, deadline, typed) {
9899
10506
  await new Promise((resolve5) => setTimeout(resolve5, 100));
9900
10507
  }
9901
10508
  }
9902
- async function countReason(frame, path, count, typed) {
10509
+ async function countReason(frame, path, count2, typed) {
9903
10510
  const attribute = (v) => scrub((v ?? "").replace(/\s+/g, " "), typed).slice(0, 40);
9904
10511
  let inputs = " none visible";
9905
10512
  try {
@@ -9908,7 +10515,7 @@ async function countReason(frame, path, count, typed) {
9908
10515
  } catch {
9909
10516
  inputs = " inputs not readable";
9910
10517
  }
9911
- return `${count} visible inputs match in ${path}:${inputs}`;
10518
+ return `${count2} visible inputs match in ${path}:${inputs}`;
9912
10519
  }
9913
10520
  function typedValues(provider, card, identity) {
9914
10521
  const values = [card, provider.expiry, provider.cvc, identity.firstName, identity.lastName, `${identity.firstName} ${identity.lastName}`];
@@ -9946,14 +10553,18 @@ function isCartRequest(r) {
9946
10553
  const url = new URL(r.url);
9947
10554
  return CART_AJAX.test(url.search) || (r.method === "GET" ? CART_ADD_PATH.test(url.pathname) : CART_WRITE_PATH.test(url.pathname) || CART_MUTATION.test(r.postData ?? ""));
9948
10555
  }
9949
- function createCartCheck(pattern) {
10556
+ function cartRequestTest(pattern) {
9950
10557
  const custom = pattern === void 0 ? void 0 : new RegExp(pattern);
10558
+ return (r) => isCartRequest(r) || custom?.test(r.url) === true;
10559
+ }
10560
+ function createCartCheck(pattern) {
10561
+ const isCart = cartRequestTest(pattern);
9951
10562
  return ({ requests, responses, dataLayerEvents }) => {
9952
10563
  const accepted = (r) => {
9953
10564
  const statuses = responses.filter((x) => x.requestId === r.id).map((x) => x.status);
9954
10565
  return statuses.some((status) => status >= 200 && status < 400);
9955
10566
  };
9956
- return dataLayerEvents.some((e) => e.event !== null && CART_EVENT.test(e.event)) || requests.some((r) => (isCartRequest(r) || custom?.test(r.url) === true) && accepted(r));
10567
+ return dataLayerEvents.some((e) => e.event !== null && CART_EVENT.test(e.event)) || requests.some((r) => isCart(r) && accepted(r));
9957
10568
  };
9958
10569
  }
9959
10570
  var defaultCartCheck = createCartCheck();
@@ -10212,11 +10823,24 @@ async function waitForUrl(recorder, url, timeout) {
10212
10823
  await recorder.wait(100);
10213
10824
  }
10214
10825
  }
10826
+ function cartAnswerNote(activity, isCart) {
10827
+ const cart = new Set(activity.requests.filter((r) => r.outcome !== "failed" && isCart(r)).map((r) => r.id));
10828
+ const answers = activity.responses.filter((x) => cart.has(x.requestId) && x.status >= 400);
10829
+ const last = answers.at(-1);
10830
+ if (last === void 0) return "";
10831
+ const request = activity.requests.find((r) => r.id === last.requestId);
10832
+ if (request === void 0) return "";
10833
+ const path = new URL(request.url).pathname.split("/").map((segment) => isValueSegment(segment) ? OTHER_NAME : segment).join("/");
10834
+ return `: the store answered ${last.status}${last.status === 429 ? " (rate limited)" : ""} to ${path}`;
10835
+ }
10215
10836
  async function waitForCart(recorder, record, scenario, options) {
10216
10837
  const check = options.cartCheck ?? createCartCheck(scenario.options.cartRequest);
10217
10838
  const deadline = Date.now() + (options.cartTimeoutMs ?? 5e3);
10218
10839
  while (!check(recorder.stepActivity(record))) {
10219
- if (Date.now() >= deadline) throw new Error("click did not add to cart");
10840
+ if (Date.now() >= deadline) {
10841
+ const note = options.cartCheck ? "" : cartAnswerNote(recorder.stepActivity(record), cartRequestTest(scenario.options.cartRequest));
10842
+ throw new Error(`click did not add to cart${note}`);
10843
+ }
10220
10844
  await recorder.wait(100);
10221
10845
  }
10222
10846
  }
@@ -10538,6 +11162,7 @@ Options for suite:
10538
11162
  --site <url> The site to test. Without --site and --stores, site in tagreeve/config.yml is used, or else tagreeve/stores.json
10539
11163
  --stores <file> A stores.json file: run every scenario against each store (instead of --site). Default: tagreeve/stores.json
10540
11164
  --variant <name[=file]> A GTM build to test (repeatable). "published" is the live container; name=file serves an override file. Default: published
11165
+ --consent <list> Run every scenario once for each consent state in the comma-separated list of accept, reject, none, withdraw. Not with --baseline or a second --variant
10541
11166
  --with-handoff Also run scenarios with handoff steps, last, headed
10542
11167
  --with-test-payment Also run scenarios with a payment step. Needs --allow-test-payment
10543
11168
  --allow-test-payment <host> The host that may run test payments. It must equal the --site host and be in the test-payment-hosts.json allowlist
@@ -10676,6 +11301,15 @@ function helpText(topic) {
10676
11301
  return topic ? HELP_TEXT[topic] : USAGE;
10677
11302
  }
10678
11303
  var NET_LOG_NEEDS_LIVE = "--net-log needs --network live. In stub mode it would let the requests a frame sends while it unloads leave the machine.";
11304
+ function parseConsent(text2) {
11305
+ const states = [];
11306
+ for (const entry of text2.split(",")) {
11307
+ if (!isConsentState(entry)) throw new UsageError(`--consent takes a comma-separated list of ${CONSENT_STATES.join(", ")}, got "${entry}"`, "suite");
11308
+ if (states.includes(entry)) throw new UsageError(`--consent lists "${entry}" twice`, "suite");
11309
+ states.push(entry);
11310
+ }
11311
+ return states;
11312
+ }
10679
11313
  function parseVariants(entries) {
10680
11314
  const variants2 = [];
10681
11315
  for (const entry of entries.length ? entries : [PUBLISHED_VARIANT]) {
@@ -10707,6 +11341,7 @@ var OPTIONS = {
10707
11341
  "server-container": { type: "boolean" },
10708
11342
  "server-container-config": { type: "string" },
10709
11343
  baseline: { type: "string" },
11344
+ consent: { type: "string" },
10710
11345
  variant: { type: "string", multiple: true },
10711
11346
  "with-handoff": { type: "boolean" },
10712
11347
  "with-test-payment": { type: "boolean" },
@@ -10857,13 +11492,20 @@ function parseCommand(argv) {
10857
11492
  for (const flag2 of ["gtm-override", "headed", "net-log"]) {
10858
11493
  if (values[flag2] !== void 0) throw new UsageError(`--${flag2} is not an option of suite`);
10859
11494
  }
11495
+ const variants2 = parseVariants(values.variant ?? []);
11496
+ const consent = values.consent === void 0 ? void 0 : parseConsent(values.consent);
11497
+ if (consent) {
11498
+ if (baseline.value !== void 0 || baseline.bare) throw new UsageError("--consent cannot be used with --baseline. A baseline file belongs to one scenario, store and variant.", "suite");
11499
+ if (variants2.length > 1) throw new UsageError("--consent cannot be used with more than one --variant.", "suite");
11500
+ }
10860
11501
  return {
10861
11502
  command: "suite",
10862
11503
  ...rest[0] !== void 0 && { dir: rest[0] },
10863
11504
  ...values.site !== void 0 && { site: values.site },
10864
11505
  ...values.stores !== void 0 && { stores: values.stores },
10865
11506
  ...values.config !== void 0 && { config: values.config },
10866
- variants: parseVariants(values.variant ?? []),
11507
+ variants: variants2,
11508
+ ...consent && { consent },
10867
11509
  network,
10868
11510
  out: values.out,
10869
11511
  ...values.label !== void 0 && { label: values.label },
@@ -10882,7 +11524,7 @@ function parseCommand(argv) {
10882
11524
  json: values.json ?? false
10883
11525
  };
10884
11526
  }
10885
- for (const flag2 of ["variant", "with-handoff", "with-test-payment", "stores"]) {
11527
+ for (const flag2 of ["variant", "with-handoff", "with-test-payment", "stores", "consent"]) {
10886
11528
  if (values[flag2] !== void 0) throw new UsageError(`--${flag2} is not an option of run`);
10887
11529
  }
10888
11530
  return {
@@ -10954,6 +11596,7 @@ function describePushDiff(d) {
10954
11596
  ...d.eventsAdded.map((r) => `new event ${r.event} ${at(r)}`),
10955
11597
  ...d.pathsRemoved.map((p) => `missing path ${p.path} (${p.types.join("|")}) in ${named(p)} ${at(p)}`),
10956
11598
  ...d.pathsAdded.map((p) => `new path ${p.path} (${p.types.join("|")}) in ${named(p)} ${at(p)}`),
11599
+ ...d.pathsMoved.map((p) => `moved path ${p.path} (${p.types.join("|")}) in ${named(p)} from epoch ${p.from} to ${p.to} [frame ${p.frame}]`),
10957
11600
  ...d.typeChanges.map((p) => `type change ${p.path}: ${p.a.join("|")} -> ${p.b.join("|")} in ${named(p)} ${at(p)}`),
10958
11601
  ...d.moved.map(
10959
11602
  (m) => m.kind === "frame" ? `moved event ${named(m)} from frame ${m.from} to ${m.to} [epoch ${m.epoch}]` : `moved event ${named(m)} from epoch ${m.from} to ${m.to} [frame ${m.frame}]`
@@ -11212,9 +11855,10 @@ function defaultBaselineName(run) {
11212
11855
  }
11213
11856
  const unsafe = (part) => /[/\\\0]/.test(part) || part.includes("..") || part.startsWith(".");
11214
11857
  const name = scenarioName(run.scenario);
11215
- const bad2 = !name || unsafe(name) ? "scenario" : unsafe(run.store ?? "") || run.store !== void 0 && !STORE_NAME.test(run.store) ? "store" : unsafe(run.variant ?? "") || run.variant !== void 0 && !VARIANT_NAME.test(run.variant) ? "variant" : void 0;
11858
+ const bad2 = !name || unsafe(name) ? "scenario" : unsafe(run.store ?? "") || run.store !== void 0 && !STORE_NAME.test(run.store) ? "store" : unsafe(run.variant ?? "") || run.variant !== void 0 && !VARIANT_NAME.test(run.variant) ? "variant" : run.consentCell !== void 0 && !isConsentState(run.consentCell) ? "consent state" : void 0;
11216
11859
  if (bad2) throw new BaselineError(`The ${bad2} in this record cannot name a baseline file. Give the baseline path.`, "usage");
11217
- return baselineFileName(run.scenario, run.store, run.variant);
11860
+ const plain = baselineFileName(run.scenario, run.store, run.variant);
11861
+ return run.consentCell === void 0 ? plain : join7("consent", run.consentCell, plain);
11218
11862
  }
11219
11863
  function insideBaselines(path) {
11220
11864
  const rel = relative(resolve2(DEFAULT_BASELINES), resolve2(path));
@@ -11230,6 +11874,7 @@ function compareBaseline(baseline, records) {
11230
11874
  const epochOrder2 = [...records.consentEpochs].sort((x, y) => x.startT - y.startT).map((e) => e.label);
11231
11875
  const diff = diffShapes(baseline.keys, hitShape(records, { byPage: baseline.byPage }), { epochOrder: epochOrder2 });
11232
11876
  warnings.push(...diff.moved.map(describeMove));
11877
+ warnings.push(...diff.gcdLetters.map((g) => `gcd letters changed for ${keyLabel(g.key)}: ${g.a} -> ${g.b} (same consent state). This is not drift.`));
11233
11878
  if (baseline.dataLayer === void 0) {
11234
11879
  warnings.push("dataLayer pushes not compared: the baseline has no push shapes (saved before 0.6.0-rc.2). Save it again to compare them.");
11235
11880
  } else {
@@ -11505,10 +12150,11 @@ var NOTE_TEXT = {
11505
12150
  nestedNameOnly: "a plain name matches a top-level field only; use **.name to match at any depth",
11506
12151
  serverSendProbableLink: "a server container hit is placed by a probable link to a browser hit, which cannot fail a run",
11507
12152
  serverSendUnlinked: "cannot evaluate: a server container hit has no link to a browser hit, so no consent state applies",
12153
+ serverContainerRejected: "cannot evaluate: the server container rejected most browser requests",
11508
12154
  noTagReports: `cannot evaluate: no tag report from this container. For web tags, install the reporter and run with --gtm-override: ${TAG_REPORTER_HINT}`,
11509
12155
  tagNameUnknown: "cannot evaluate: the tag has no name in its report or in expectedTags"
11510
12156
  };
11511
- var CANNOT_EVALUATE_NOTES = ["cannotEvaluateBody", "fieldsNotRecorded", "serverSendUnlinked", "noTagReports", "tagNameUnknown"];
12157
+ var CANNOT_EVALUATE_NOTES = ["cannotEvaluateBody", "fieldsNotRecorded", "serverSendUnlinked", "serverContainerRejected", "noTagReports", "tagNameUnknown"];
11512
12158
  var WORST_FIRST = ["leak", "unchecked", "mixed", "early", "full", "ping"];
11513
12159
  var CONSENT_FIELDS = ["analytics", "ads", "adUserData", "adPersonalization"];
11514
12160
  var MAX_EVIDENCE = 5;
@@ -11606,7 +12252,7 @@ function namedLeaks(results) {
11606
12252
  return named;
11607
12253
  }
11608
12254
  var NO_LINK = "no link to a browser hit";
11609
- function judge(hit, state, undecided, named, unlinked = false) {
12255
+ function judge2(hit, state, undecided, named, unlinked = false) {
11610
12256
  if (unlinked) {
11611
12257
  return hit.idFields === void 0 || hit.idFields.length > 0 ? { mark: "unchecked", label: `${NO_LINK}, consent state unknown` } : { mark: "full", label: NO_LINK };
11612
12258
  }
@@ -11666,16 +12312,69 @@ function flagViews(records) {
11666
12312
  }
11667
12313
  byKind.set(flag2.kind, entry);
11668
12314
  }
11669
- return [...byKind].map(([kind, { count, hosts }]) => {
12315
+ return [...byKind].map(([kind, { count: count2, hosts }]) => {
11670
12316
  const names = [...hosts.keys()].sort();
11671
12317
  return {
11672
12318
  kind,
11673
- count,
12319
+ count: count2,
11674
12320
  hosts: names,
11675
12321
  ...kind === "platformHost" && { hostCounts: names.map((host) => ({ host, count: hosts.get(host) })) }
11676
12322
  };
11677
12323
  }).sort((a, b) => a.kind.localeCompare(b.kind));
11678
12324
  }
12325
+ var SKIP_REASONS = ["compressed or binary body", "body cut at 64 KiB", "net-log request with no body"];
12326
+ function searchView(search) {
12327
+ const num = (re) => {
12328
+ const m = re.exec(search.detail)?.[1];
12329
+ return m === void 0 ? void 0 : Number(m);
12330
+ };
12331
+ return {
12332
+ forms: /\bas (plain text.+?)\. Searched:/.exec(search.detail)?.[1],
12333
+ requests: num(/Searched (\d+) requests?/),
12334
+ skipped: search.recordIds.length,
12335
+ reasons: SKIP_REASONS.map((reason) => ({ reason, count: num(new RegExp(`${reason} (\\d+)`)) ?? 0 })).filter((r) => r.count > 0)
12336
+ };
12337
+ }
12338
+ function routeSource(route) {
12339
+ const from = route.source.source === "identity" ? `identity ${route.source.name}` : `url param ${route.source.name}`;
12340
+ const via = route.hops.flatMap((h) => h.kind === "cookie" ? [`cookie ${h.name}`] : []);
12341
+ return [from, ...via].join(" via ");
12342
+ }
12343
+ function routeLine2(sources, route, requests) {
12344
+ const where2 = route.kind === "pageUrl" ? "page URL only" : route.kind;
12345
+ return `${sources.join(", ")}, field ${route.sink.field}, ${route.sink.transform} (${where2}), ${requests} request${requests === 1 ? "" : "s"}`;
12346
+ }
12347
+ function routesView(records, epochs, graceMs) {
12348
+ const search = records.flags.find((f) => f.kind === "canarySearch");
12349
+ if (!search) return void 0;
12350
+ const groups = /* @__PURE__ */ new Map();
12351
+ for (const flag2 of records.flags) {
12352
+ const route = flag2.route;
12353
+ if (flag2.kind !== "identifierRoute" || !route) continue;
12354
+ const request = records.requests.find((r) => r.id === route.sink.requestId);
12355
+ const epoch = request ? epochForHit(epochs, request.t, graceMs)?.label ?? "undecided" : "unknown";
12356
+ const judged = identifierRoute([search, flag2, ...epochs, ...records.requests, ...records.hits], graceMs);
12357
+ const stored = records.results.find((r) => r.expectation === "builtin: identifierRoute");
12358
+ const failing = judged !== void 0 && !judged.pass && (!stored || !stored.pass && stored.evidence.includes(route.sink.requestId));
12359
+ const verdict = !failing ? "PASS" : judged.severity === "warn" || stored?.severity === "warn" ? "WARN" : "FAIL";
12360
+ const key = JSON.stringify([route.sink.host, route.sink.field, route.sink.transform, route.kind, epoch, verdict]);
12361
+ let group = groups.get(key);
12362
+ if (!group) groups.set(key, group = { route, epoch, verdict, sources: [], requestIds: /* @__PURE__ */ new Set(), flags: 0 });
12363
+ const source = routeSource(route);
12364
+ if (!group.sources.includes(source)) group.sources.push(source);
12365
+ group.requestIds.add(route.sink.requestId);
12366
+ group.flags += 1;
12367
+ }
12368
+ const rows = [...groups.values()].map((g) => ({
12369
+ line: routeLine2(g.sources, g.route, g.requestIds.size),
12370
+ host: g.route.sink.host,
12371
+ epoch: g.epoch,
12372
+ verdict: g.verdict,
12373
+ flags: g.flags,
12374
+ requests: g.requestIds.size
12375
+ }));
12376
+ return { rows, search: searchView(search) };
12377
+ }
11679
12378
  function buildReportModel(records) {
11680
12379
  const { run } = records;
11681
12380
  const graceMs = run.graceWindowMs ?? DEFAULT_GRACE_MS;
@@ -11690,7 +12389,7 @@ function buildReportModel(records) {
11690
12389
  const state = effectiveConsentAt(hit, epochs, graceMs, index);
11691
12390
  const column = unlinked ? epochs.length : epoch ? epochs.indexOf(epoch) : -1;
11692
12391
  const probable = server && hit.via?.confidence === "probable";
11693
- return { hit, state, column, server, unlinked, probable, verdict: judge(hit, state, !unlinked && (!epoch || epoch.label === "undecided"), named, unlinked) };
12392
+ return { hit, state, column, server, unlinked, probable, verdict: judge2(hit, state, !unlinked && (!epoch || epoch.label === "undecided"), named, unlinked) };
11694
12393
  });
11695
12394
  const synthetic = epochs.length === 0 || placed.some((p) => p.column < 0);
11696
12395
  const offset = synthetic ? 1 : 0;
@@ -11739,6 +12438,7 @@ function buildReportModel(records) {
11739
12438
  return { vendor, names: [...names].sort() };
11740
12439
  }).filter((v) => v.names.length > 0);
11741
12440
  }
12441
+ const routes2 = routesView(records, epochs, graceMs);
11742
12442
  return {
11743
12443
  header: {
11744
12444
  scenario: run.scenario,
@@ -11758,7 +12458,8 @@ function buildReportModel(records) {
11758
12458
  flags: flagViews(records),
11759
12459
  fields: fields2,
11760
12460
  skippedFields: (records.steps ?? []).flatMap((s) => (s.skippedFields ?? []).map((selector) => ({ step: s.label, selector }))),
11761
- ...serverContainer && { serverContainer }
12461
+ ...serverContainer && { serverContainer },
12462
+ ...routes2 && { routes: routes2 }
11762
12463
  };
11763
12464
  }
11764
12465
 
@@ -11826,22 +12527,22 @@ function list2(names) {
11826
12527
  const all = [...names].sort(byVendorName).map(vendorName);
11827
12528
  return all.length < 2 ? all.join("") : `${all.slice(0, -1).join(", ")} and ${all.at(-1)}`;
11828
12529
  }
11829
- var plural2 = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
12530
+ var plural3 = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
11830
12531
  function checkParts(checks, verb, inRuns) {
11831
- return [...checks].sort(([a], [b]) => a.localeCompare(b)).map(([name, runs]) => `built-in check ${name} ${verb}${inRuns ? ` in ${plural2(runs, "run")}` : ""}`);
12532
+ return [...checks].sort(([a], [b]) => a.localeCompare(b)).map(([name, runs]) => `built-in check ${name} ${verb}${inRuns ? ` in ${plural3(runs, "run")}` : ""}`);
11832
12533
  }
11833
12534
  function findingsSentence(f, inRuns = false) {
11834
12535
  const parts = [];
11835
12536
  for (const [label, vendors] of [...f.hits].sort(([a], [b]) => a.localeCompare(b))) parts.push(`${list2(vendors)} ${vendors.size === 1 ? "sends" : "send"} hits in the ${label} state`);
11836
12537
  for (const [label, vendors] of [...f.identifiers].sort(([a], [b]) => a.localeCompare(b))) parts.push(`identifiers go out to ${list2(vendors)} in the ${label} state`);
11837
12538
  if (parts.length === 0 && f.unchecked === 0) parts.push("no leaks");
11838
- if (f.failed > 0) parts.push(`${plural2(f.failed, "rule")} failed`);
12539
+ if (f.failed > 0) parts.push(`${plural3(f.failed, "rule")} failed`);
11839
12540
  parts.push(...checkParts(f.failedChecks, "failed", inRuns));
11840
- if (f.unchecked > 0) parts.push(`${plural2(f.unchecked, "expectation")} could not be checked`);
11841
- if (f.warned > 0) parts.push(`${plural2(f.warned, "rule")} warned`);
12541
+ if (f.unchecked > 0) parts.push(`${plural3(f.unchecked, "expectation")} could not be checked`);
12542
+ if (f.warned > 0) parts.push(`${plural3(f.warned, "rule")} warned`);
11842
12543
  parts.push(...checkParts(f.warnedChecks, "warned", inRuns));
11843
- if (f.unlinkedServerHits > 0) parts.push(`${plural2(f.unlinkedServerHits, "server container hit")} could not be linked to a browser hit`);
11844
- if (f.probableServerHits > 0) parts.push(`${plural2(f.probableServerHits, "server container hit")} placed by a probable link`);
12544
+ if (f.unlinkedServerHits > 0) parts.push(`${plural3(f.unlinkedServerHits, "server container hit")} could not be linked to a browser hit`);
12545
+ if (f.probableServerHits > 0) parts.push(`${plural3(f.probableServerHits, "server container hit")} placed by a probable link`);
11845
12546
  return parts.join("; ");
11846
12547
  }
11847
12548
  function runVerdict(model) {
@@ -11888,8 +12589,8 @@ function glyph(mark) {
11888
12589
  }
11889
12590
  function segmentCell(segment) {
11890
12591
  const label = segment.label ? `<span class="why">${escapeHtml(segment.label)}</span>` : "";
11891
- const count = segment.hits ? `<span class="count">${segment.hits} hit${segment.hits === 1 ? "" : "s"}${segment.probable ? `, ${segment.probable} by probable link` : ""}</span>` : "";
11892
- return `<td class="m-${segment.mark}">${glyph(segment.mark)}<span class="name">${MARK_NAME[segment.mark]}</span>${count}${label}</td>`;
12592
+ const count2 = segment.hits ? `<span class="count">${segment.hits} hit${segment.hits === 1 ? "" : "s"}${segment.probable ? `, ${segment.probable} by probable link` : ""}</span>` : "";
12593
+ return `<td class="m-${segment.mark}">${glyph(segment.mark)}<span class="name">${MARK_NAME[segment.mark]}</span>${count2}${label}</td>`;
11893
12594
  }
11894
12595
  var SERVER_CAVEAT = "Server container rows show what the local container sent on. Stape-only features, tags that need the hosting layer, unpublished workspaces and calls that no decoder matched are not shown. Hits with no link to a browser hit are in the unlinked column.";
11895
12596
  function timeline(model) {
@@ -11934,6 +12635,24 @@ function skippedFields(model, level) {
11934
12635
  <${level}>Skipped fields</${level}>
11935
12636
  <ul class="fields">${items}</ul>`;
11936
12637
  }
12638
+ var VERDICT_CLASS = { PASS: "full", WARN: "ping", FAIL: "leak" };
12639
+ function routes(model) {
12640
+ if (!model.routes) return "";
12641
+ const { rows, search } = model.routes;
12642
+ const table = rows.length === 0 ? '<p class="empty">No planted value was found in a request to a non-first-party host.</p>' : `<div class="scroll"><table><thead><tr><th scope="col">Route</th><th scope="col">Sink host</th><th scope="col">Epoch at sink</th><th scope="col">Verdict</th></tr></thead><tbody>${rows.map((r) => `<tr><td>${escapeHtml(r.line)}</td><td>${escapeHtml(r.host)}</td><td>${escapeHtml(r.epoch)}</td><td class="m-${VERDICT_CLASS[r.verdict]}"><strong>${r.verdict}</strong></td></tr>`).join("")}</tbody></table></div>`;
12643
+ const plural4 = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
12644
+ const reasons = search.reasons.length ? ` (${search.reasons.map((r) => `${r.count} ${r.reason}`).join(", ")})` : "";
12645
+ const items = [
12646
+ ...search.forms ? [`Forms searched: ${search.forms}.`] : [],
12647
+ "Parts searched: URL, body and decoded fields.",
12648
+ "Parts not searched: request headers, including Referer and Cookie.",
12649
+ ...search.requests !== void 0 ? [`Requests searched: ${plural4(search.requests, "request")} to non-first-party hosts.`] : [],
12650
+ `Skipped: ${plural4(search.skipped, "request")}${reasons}.`
12651
+ ];
12652
+ return `${table}
12653
+ <p><strong>Searched and skipped</strong></p>
12654
+ <ul class="fields">${items.map((i) => `<li>${escapeHtml(i)}</li>`).join("")}</ul>`;
12655
+ }
11937
12656
  var STYLE = `
11938
12657
  :root{color-scheme:light dark;--bg:#fff;--fg:#1b1f24;--muted:#57606a;--line:#d0d7de;--card:#f6f8fa;--full:#1a7f37;--ping:#9a6700;--nothing:#6e7781;--leak:#cf222e;--unchecked:#8250df;--mixed:#bc4c00;--early:#0969da}
11939
12658
  @media (prefers-color-scheme:dark){:root{--bg:#0d1117;--fg:#e6edf3;--muted:#8d96a0;--line:#30363d;--card:#161b22;--full:#3fb950;--ping:#d29922;--nothing:#8b949e;--leak:#ff7b72;--unchecked:#d2a8ff;--mixed:#ffa657;--early:#58a6ff}}
@@ -11993,7 +12712,9 @@ ${timeline(model)}
11993
12712
  <${level}>Expectations</${level}>
11994
12713
  ${expectations(model)}
11995
12714
  <${level}>Flags</${level}>
11996
- ${flags(model)}
12715
+ ${flags(model)}${model.routes ? `
12716
+ <${level}>Identifier routes</${level}>
12717
+ ${routes(model)}` : ""}
11997
12718
  <${level}>Fields seen while a signal was denied</${level}>
11998
12719
  ${fields(model)}${skippedFields(model, level)}`;
11999
12720
  }
@@ -12154,11 +12875,18 @@ var PATH_EXAMPLES = 3;
12154
12875
  var SANDBOX_PATH_EXAMPLES = 1;
12155
12876
  var PURPOSE_ORDER = ["telemetry", "checkout", "payments", "cdn"];
12156
12877
  var GROUPED_KINDS = /* @__PURE__ */ new Set(["unknownDestination", "firstPartySubdomain"]);
12157
- function countHits(hits) {
12878
+ function maskCanaries(text2, canaries = []) {
12879
+ if (canaries.length === 0) return text2;
12880
+ const forms = [...canaryPool(canaries, null).forms].sort((a, b) => b[0].length - a[0].length);
12881
+ let out = text2;
12882
+ for (const [form, name] of forms) out = out.split(form).join(`(url param ${name})`);
12883
+ return out;
12884
+ }
12885
+ function countHits(hits, canaries = []) {
12158
12886
  const out = {};
12159
12887
  for (const hit of hits) {
12160
12888
  const events = out[hit.vendor] ??= {};
12161
- const name = hit.event ?? "(no event)";
12889
+ const name = maskCanaries(hit.event ?? "(no event)", canaries);
12162
12890
  events[name] = (events[name] ?? 0) + 1;
12163
12891
  }
12164
12892
  return out;
@@ -12198,13 +12926,15 @@ function serverContainerOf(records) {
12198
12926
  unlinked: sent.length - linked.length,
12199
12927
  forwarded: serverjs + config + destination,
12200
12928
  notExact: notExactCounts(sent),
12201
- ...container.error && { error: container.error }
12929
+ ...container.error && { error: container.error },
12930
+ ...container.loaderUnwrapped && { loaderUnwrapped: container.loaderUnwrapped.requests }
12202
12931
  };
12203
12932
  }
12204
12933
  function buildSummary(records, results, path) {
12205
12934
  const testPayment = testPaymentOf(records);
12206
12935
  const serverContainer = serverContainerOf(records);
12207
12936
  const dataLayer = pushShapes({ steps: records.steps, dataLayerEvents: records.dataLayerEvents ?? [] });
12937
+ for (const step of dataLayer.steps) for (const shape of step.events) shape.event = maskCanaries(shape.event, records.run.canaries);
12208
12938
  const tags = summarizeTags(records.tagReports ?? [], expectedTagsOf(records.run));
12209
12939
  return {
12210
12940
  runId: records.run.id,
@@ -12212,11 +12942,12 @@ function buildSummary(records, results, path) {
12212
12942
  path,
12213
12943
  pass: results.every((r) => r.pass),
12214
12944
  ok: results.every(passesGate),
12215
- hits: countHits(records.hits),
12945
+ hits: countHits(records.hits, records.run.canaries),
12216
12946
  ...dataLayer.pushes > 0 && { dataLayer },
12217
12947
  ...tags && { tags },
12218
12948
  epochs: records.consentEpochs.map((e) => ({ label: e.label, state: stateName(e.state), startT: e.startT, endT: e.endT })),
12219
12949
  flags: records.flags.map((f) => ({ kind: f.kind, detail: redactFlagDetail(f.detail, f.kind) })),
12950
+ ...records.run.canaries && { canaries: [...records.run.canaries.map((c) => c.name), "email", "phone"] },
12220
12951
  ...testPayment && { testPayment },
12221
12952
  ...records.run.testServerContainer && { testServerContainer: true },
12222
12953
  ...serverContainer && { serverContainer },
@@ -12237,12 +12968,19 @@ function passesGate(r) {
12237
12968
  function exitCodeFor(results) {
12238
12969
  return results.every(passesGate) ? 0 : 1;
12239
12970
  }
12971
+ var ROUTE_LINES = 5;
12240
12972
  function formatFlags(flags2) {
12241
12973
  const lines = [];
12242
12974
  const groups = /* @__PURE__ */ new Map();
12243
12975
  let realData = 0;
12244
12976
  let realDataPush = 0;
12977
+ let routes2 = 0;
12245
12978
  for (const f of flags2) {
12979
+ if (f.kind === "identifierRoute") {
12980
+ routes2 += 1;
12981
+ if (routes2 <= ROUTE_LINES) lines.push(` identifierRoute: ${f.detail}`);
12982
+ continue;
12983
+ }
12246
12984
  if (f.kind === "possibleRealData") {
12247
12985
  realData += 1;
12248
12986
  continue;
@@ -12264,11 +13002,12 @@ function formatFlags(flags2) {
12264
13002
  group.paths.add(url.pathname);
12265
13003
  groups.set(key, group);
12266
13004
  }
12267
- for (const { kind, host, count, paths } of groups.values()) {
13005
+ for (const { kind, host, count: count2, paths } of groups.values()) {
12268
13006
  const shown2 = [...paths].slice(0, kind === "sandboxPageUrl" ? SANDBOX_PATH_EXAMPLES : PATH_EXAMPLES);
12269
13007
  const more = paths.size - shown2.length;
12270
- lines.push(` ${kind}: ${host} x${count} (${shown2.join(", ")}${more > 0 ? ` and ${more} more` : ""})`);
13008
+ lines.push(` ${kind}: ${host} x${count2} (${shown2.join(", ")}${more > 0 ? ` and ${more} more` : ""})`);
12271
13009
  }
13010
+ if (routes2 > ROUTE_LINES) lines.push(` ${routes2 - ROUTE_LINES} more routes in the record`);
12272
13011
  if (realData > 0) lines.push(` possibleRealData: x${realData}`);
12273
13012
  if (realDataPush > 0) lines.push(` possibleRealDataPush: x${realDataPush}`);
12274
13013
  lines.push(...platformHostLines(flags2));
@@ -12277,7 +13016,7 @@ function formatFlags(flags2) {
12277
13016
  var URL_TOKEN = /[a-z][a-z0-9+.-]*:\/\/\S+/gi;
12278
13017
  var URL_PARTS = /^(?:(?:([a-z][a-z0-9+.-]*:)?\/\/)([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#.*)?$/is;
12279
13018
  var RECEIVED_PAGE = /^(\S+ received )(.+)( as the page)$/s;
12280
- var PROSE_KINDS = /* @__PURE__ */ new Set(["possibleRealData", "possibleRealDataPush", "unloadGap", "netLogUnreadable", "serverContainerFailed", "dataLayerReassigned", "dataLayerNotHooked", "dataLayerIncomplete"]);
13019
+ var PROSE_KINDS = /* @__PURE__ */ new Set(["possibleRealData", "possibleRealDataPush", "unloadGap", "netLogUnreadable", "serverContainerFailed", "dataLayerReassigned", "dataLayerNotHooked", "dataLayerIncomplete", "identifierRoute", "canarySearch"]);
12281
13020
  var URL_AT_END = /^(.*?(?:\b[A-Z]+ |: ))((?:[a-z][a-z0-9+.-]*:)?\/\/.*|\/.*)$/s;
12282
13021
  function queryName(pair) {
12283
13022
  const eq = pair.indexOf("=");
@@ -12331,7 +13070,8 @@ function serverContainerLines(summary) {
12331
13070
  if (!c) return testServerContainer ? [`Server container: ${head}${rejectedSuffix(summary)}`] : [];
12332
13071
  const error = testServerContainer && c.error ? `, failed (${c.error})` : "";
12333
13072
  const calls = `${c.calls} vendor call${c.calls === 1 ? "" : "s"}, ${c.exact} linked exactly, ${c.probable} probable, ${c.unlinked} unlinked`;
12334
- return [`Server container: ${head}${error}; ${calls}; ${c.forwarded} request${c.forwarded === 1 ? "" : "s"} forwarded to Google${c.error ? "" : rejectedSuffix(summary)}`, SERVER_CONTAINER_LIMITS];
13073
+ const loader = c.loaderUnwrapped ? `; ${c.loaderUnwrapped} Stape loader request${c.loaderUnwrapped === 1 ? "" : "s"} sent as their real path` : "";
13074
+ return [`Server container: ${head}${error}; ${calls}; ${c.forwarded} request${c.forwarded === 1 ? "" : "s"} forwarded to Google${c.error ? "" : rejectedSuffix(summary)}${loader}`, SERVER_CONTAINER_LIMITS];
12335
13075
  }
12336
13076
  var DATALAYER_EVENTS_SHOWN = 3;
12337
13077
  function dataLayerLabelRank({ event, kind }) {
@@ -12374,6 +13114,7 @@ function formatSummary(summary) {
12374
13114
  const { provider, host, testMode } = summary.testPayment;
12375
13115
  lines.push(`TEST PAYMENT: ${provider} on ${host} (test mode ${testMode === "declared" ? "declared" : "on page"})`);
12376
13116
  }
13117
+ if (summary.canaries) lines.push(`Canaries: ${summary.canaries.filter((n) => n !== "email" && n !== "phone").join(", ")} on the start URL; identity email and phone`);
12377
13118
  lines.push(...serverContainerLines(summary));
12378
13119
  lines.push("Hits");
12379
13120
  const vendors = Object.entries(summary.hits);
@@ -12556,19 +13297,21 @@ function storeCellSite(site) {
12556
13297
  return new URL(site).origin;
12557
13298
  }
12558
13299
  async function labelRecord(path, spec) {
12559
- const { label, store, variant, out, site } = spec;
12560
- if (label === void 0 && store === void 0 && !variant) return path;
13300
+ const { label, store, consentCell, variant, out, site, canaries } = spec;
13301
+ if (label === void 0 && store === void 0 && !variant && !canaries) return path;
12561
13302
  const text2 = await readFile8(path, "utf8");
12562
13303
  const newline = text2.indexOf("\n");
12563
13304
  const run = {
12564
13305
  ...JSON.parse(text2.slice(0, newline)),
12565
13306
  ...label !== void 0 && { label },
12566
13307
  ...store !== void 0 && { store, site: storeCellSite(site) },
13308
+ ...consentCell !== void 0 && { consentCell },
13309
+ ...canaries && { canaries },
12567
13310
  ...variant && { variant: variant.name }
12568
13311
  };
12569
13312
  await writeFile4(path, `${JSON.stringify(run)}${text2.slice(newline)}`);
12570
13313
  if (!variant) return path;
12571
- const target = join12(out, `${variant.fileStem}.${variant.name}.jsonl`);
13314
+ const target = join12(out, `${[variant.fileStem, consentCell, variant.name].filter(Boolean).join(".")}.jsonl`);
12572
13315
  await rename(path, target);
12573
13316
  return target;
12574
13317
  }
@@ -12585,17 +13328,61 @@ function declarationHint(spec, label) {
12585
13328
  if (hints.length === 0) return void 0;
12586
13329
  return `Declare it in ${testPaymentHostsPath()} with ${hints.join(" or ")} if this store is in test mode.`;
12587
13330
  }
13331
+ function queryNames(start) {
13332
+ const query = start.split("#")[0].split("?").slice(1).join("?");
13333
+ return query.split("&").map((pair) => {
13334
+ const raw = pair.split("=")[0];
13335
+ try {
13336
+ return decodeURIComponent(raw.replace(/\+/g, " "));
13337
+ } catch {
13338
+ return raw;
13339
+ }
13340
+ });
13341
+ }
13342
+ function withCanaries(start, canaries, probe2 = start) {
13343
+ const hash = start.indexOf("#");
13344
+ const base2 = hash < 0 ? start : start.slice(0, hash);
13345
+ const tail = hash < 0 ? "" : start.slice(hash);
13346
+ const probeHash = probe2.indexOf("#");
13347
+ const probeBase = probeHash < 0 ? probe2 : probe2.slice(0, probeHash);
13348
+ const added = canaries.map((c) => `${c.name}=${encodeURIComponent(c.value)}`).join("&");
13349
+ return `${base2}${probeBase.includes("?") ? /[?&]$/.test(probeBase) ? "" : "&" : "?"}${added}${tail}`;
13350
+ }
13351
+ var nameCanaries = maskCanaries;
13352
+ async function scrubStepErrors(path, canaries) {
13353
+ const lines = (await readFile8(path, "utf8")).split("\n");
13354
+ const kept = lines.map((line, i) => i > 0 && line.startsWith('{"type":"step"') ? nameCanaries(line, canaries) : line);
13355
+ await writeFile4(path, kept.join("\n"));
13356
+ }
12588
13357
  async function executeRun(spec, rawIo) {
12589
- const { parsed, gtmOverride, variant } = spec;
13358
+ const { gtmOverride, variant } = spec;
13359
+ let parsed = spec.parsed;
13360
+ let canaries;
13361
+ let seed = spec.seed;
12590
13362
  let io = rawIo;
12591
13363
  const scrubber = gtmOverride ? new Scrubber(gtmOverride.gtmAuth) : void 0;
12592
13364
  if (scrubber) {
12593
13365
  io = { stdout: (t) => rawIo.stdout(scrubber.text(t)), stderr: (t) => rawIo.stderr(scrubber.text(t)) };
12594
13366
  }
12595
13367
  const failed = (error) => {
13368
+ if (canaries) error = nameCanaries(error, canaries);
12596
13369
  io.stderr(error);
12597
13370
  return { code: 2, error: scrubber ? scrubber.text(error) : error };
12598
13371
  };
13372
+ if (parsed.options.canaries) {
13373
+ const resolved = parsed.start.replace(/\{(\w+)\}/g, (m, name) => parsed.vars[name] ?? m);
13374
+ const held = queryNames(resolved);
13375
+ const taken = CANARY_NAMES.find((name) => held.includes(name));
13376
+ if (taken) return failed(`options.canaries: the start URL already holds the ${taken} parameter. Remove it from start, or turn canaries off.
13377
+ `);
13378
+ seed ??= parsed.options.seed ?? Math.floor(Math.random() * 2 ** 31);
13379
+ canaries = canaryValues(seed, spec.consentCell);
13380
+ const refilled = [...resolved.matchAll(/\{(\w+)\}/g)].some((m) => Object.hasOwn(parsed.vars, m[1]));
13381
+ if (refilled && Object.values(parsed.vars).some((v) => v.includes("#"))) {
13382
+ return failed("options.canaries: a variable value holds both a {placeholder} and a #, so the canary parameters could land in the URL fragment. Remove one, or turn canaries off.\n");
13383
+ }
13384
+ parsed = { ...parsed, start: refilled ? withCanaries(parsed.start, canaries, resolved) : withCanaries(resolved, canaries) };
13385
+ }
12599
13386
  let records;
12600
13387
  let path;
12601
13388
  try {
@@ -12611,7 +13398,8 @@ async function executeRun(spec, rawIo) {
12611
13398
  unloadGapIgnore: parsed.options.unloadGapIgnore,
12612
13399
  dataLayerNames: parsed.options.dataLayerNames,
12613
13400
  graceWindowMs: parsed.options.graceWindow ?? DEFAULT_GRACE_MS,
12614
- seed: spec.seed,
13401
+ seed,
13402
+ ...canaries && { canaries },
12615
13403
  headed: spec.headed,
12616
13404
  viewport: spec.viewport ?? parsed.options.viewport,
12617
13405
  netLog: spec.netLog,
@@ -12637,19 +13425,22 @@ async function executeRun(spec, rawIo) {
12637
13425
  `;
12638
13426
  const written = (error instanceof StepError || error instanceof GtmOverrideFailure || error instanceof ServerContainerFailure) && error.run ? error.run.path : void 0;
12639
13427
  if (written) {
12640
- const kept = await labelRecord(written, spec);
13428
+ const kept = await labelRecord(written, { ...spec, canaries });
13429
+ if (canaries) await scrubStepErrors(kept, canaries);
12641
13430
  text2 += `Record: ${kept}
12642
13431
  `;
12643
13432
  return { ...failed(text2), path: kept };
12644
13433
  }
12645
13434
  return failed(text2);
12646
13435
  }
12647
- path = await labelRecord(path, spec);
13436
+ path = await labelRecord(path, { ...spec, canaries });
12648
13437
  if (spec.label !== void 0) records.run.label = spec.label;
12649
13438
  if (spec.store !== void 0) {
12650
13439
  records.run.store = spec.store;
12651
13440
  records.run.site = storeCellSite(spec.site);
12652
13441
  }
13442
+ if (spec.consentCell !== void 0) records.run.consentCell = spec.consentCell;
13443
+ if (canaries) records.run.canaries = canaries;
12653
13444
  if (variant) records.run.variant = variant.name;
12654
13445
  let results = evaluate(allRecords(records), parsed);
12655
13446
  if (scrubber) results = scrubber.deep(results);
@@ -12837,24 +13628,63 @@ function diffText(d) {
12837
13628
  return parts.length ? parts.join(", ") : "no change";
12838
13629
  }
12839
13630
  function cellName(cell) {
12840
- return [cell.scenario, cell.labels.store, cell.variant].filter(Boolean).join(" ");
13631
+ return [cell.scenario, cell.labels.store, cell.labels.consent, cell.variant].filter(Boolean).join(" ");
13632
+ }
13633
+ var hitsText = (n) => n === 0 ? "0" : `${n} hit${n === 1 ? "" : "s"}`;
13634
+ function vendorLines(matrix) {
13635
+ const lines = [];
13636
+ for (const entry of matrix) {
13637
+ if (matrix.length > 1) lines.push("", `${entry.scenario}${entry.store === void 0 ? "" : ` on ${entry.store}`}`);
13638
+ else lines.push("");
13639
+ for (const v of entry.vendors) {
13640
+ const parts = CONSENT_STATES.filter((state) => v.states[state]).map((state) => {
13641
+ const extra = state === "accept" ? 0 : v.notInAccept[state]?.fields.length ?? 0;
13642
+ const text2 = `${state} ${hitsText(v.states[state].hits)}`;
13643
+ return extra > 0 ? `${text2}, ${extra} field${extra === 1 ? "" : "s"} not in accept` : text2;
13644
+ });
13645
+ lines.push(`${v.vendor}: ${parts.join("; ")}`);
13646
+ }
13647
+ }
13648
+ return lines;
13649
+ }
13650
+ async function consentMatrixOf(cells, paths) {
13651
+ const entries = [];
13652
+ const keys = /* @__PURE__ */ new Map();
13653
+ for (const c of cells) {
13654
+ if (paths.has(c)) keys.set(JSON.stringify([c.scenario, c.labels.store]), { scenario: c.scenario, ...c.labels.store !== void 0 && { store: c.labels.store } });
13655
+ }
13656
+ for (const { scenario, store } of keys.values()) {
13657
+ const records = {};
13658
+ for (const c of cells) {
13659
+ const path = paths.get(c);
13660
+ if (path === void 0 || c.scenario !== scenario || c.labels.store !== store) continue;
13661
+ const state = c.labels.consent;
13662
+ (records[state] ??= []).push(await readRun(path));
13663
+ }
13664
+ entries.push({ scenario, ...store !== void 0 && { store }, ...stateTable(records) });
13665
+ }
13666
+ return entries;
12841
13667
  }
12842
13668
  function formatSuiteTable(manifest, dir) {
12843
13669
  const [first, ...others] = manifest.variants;
12844
13670
  const scenarios = [...new Set(manifest.cells.map((c) => c.scenario))];
12845
13671
  const stores = manifest.stores.map((s) => s.name);
12846
- const header = ["scenario", ...stores.length ? ["store"] : [], ...manifest.variants, ...others.map((v) => `diff (${first} -> ${v})`)];
13672
+ const columns = manifest.consent ?? manifest.variants;
13673
+ const header = ["scenario", ...stores.length ? ["store"] : [], ...columns, ...manifest.consent ? [] : others.map((v) => `diff (${first} -> ${v})`)];
12847
13674
  const rows = scenarios.flatMap(
12848
13675
  (scenario) => (stores.length ? stores : [void 0]).map((store) => [
12849
13676
  scenario,
12850
13677
  ...store === void 0 ? [] : [store],
12851
- ...manifest.variants.map((v) => cellText(manifest.cells.find((c) => c.scenario === scenario && c.labels.store === store && c.variant === v))),
12852
- ...others.map((v) => diffText(manifest.diffs.find((d) => d.scenario === scenario && d.store === store && d.to === v)))
13678
+ ...columns.map(
13679
+ (column) => cellText(manifest.cells.find((c) => c.scenario === scenario && c.labels.store === store && (manifest.consent ? c.labels.consent === column : c.variant === column)))
13680
+ ),
13681
+ ...manifest.consent ? [] : others.map((v) => diffText(manifest.diffs.find((d) => d.scenario === scenario && d.store === store && d.to === v)))
12853
13682
  ])
12854
13683
  );
12855
13684
  const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
12856
13685
  const line = (cols) => cols.map((c, i) => i === cols.length - 1 ? c : c.padEnd(widths[i] + 3)).join("").trimEnd();
12857
13686
  const out = [line(header), ...rows.map(line)];
13687
+ out.push(...vendorLines(manifest.consentMatrix ?? []));
12858
13688
  const defaultsLine = formatDefaultsLine(manifest.defaults);
12859
13689
  if (defaultsLine) out.push("", defaultsLine);
12860
13690
  const records = manifest.cells.filter((c) => c.record);
@@ -12871,7 +13701,7 @@ function formatSuiteTable(manifest, dir) {
12871
13701
  return `${out.join("\n")}
12872
13702
  `;
12873
13703
  }
12874
- async function scan2(dir, trackers, configOptions, io) {
13704
+ async function scan3(dir, trackers, configOptions, io) {
12875
13705
  let names;
12876
13706
  try {
12877
13707
  const entries = await readdir3(dir, { withFileTypes: true });
@@ -12930,6 +13760,7 @@ async function readOverrides(args, io) {
12930
13760
  async function diffPairs(cells, variants2, stores, dir) {
12931
13761
  const diffs = [];
12932
13762
  const [first, ...others] = variants2;
13763
+ if (!others.length) return diffs;
12933
13764
  const recordOf = (scenario, store, variant) => cells.find((c) => c.scenario === scenario && c.labels.store === store && c.variant === variant)?.record;
12934
13765
  for (const scenario of [...new Set(cells.map((c) => c.scenario))]) {
12935
13766
  for (const store of stores.length ? stores : [void 0]) {
@@ -12971,6 +13802,16 @@ function scenarioFor(s, store, argVars, io) {
12971
13802
  }
12972
13803
  return { ...s.parsed, vars: { ...s.parsed.vars, ...declared }, identity };
12973
13804
  }
13805
+ function checkConsentMatrix(scenarios, states) {
13806
+ for (const s of scenarios) {
13807
+ const own = ownConsentState(s.parsed);
13808
+ if (own === void 0) throw new UsageError(`${s.name}: --consent needs a consent step in every scenario. Its answer is the one the cells replace.`, "suite");
13809
+ if (own === "withdraw") throw new UsageError(`${s.name}: the first consent step is withdraw. --consent needs a first consent step of accept, reject or none.`, "suite");
13810
+ if (states.includes("withdraw") && s.parsed.options.withdrawWith === void 0) {
13811
+ throw new UsageError(`${s.name}: --consent with withdraw needs options.withdrawWith, the selector that opens the site's cookie settings.`, "suite");
13812
+ }
13813
+ }
13814
+ }
12974
13815
  async function loadStores(path, io) {
12975
13816
  if (path === void 0) return [];
12976
13817
  try {
@@ -13020,8 +13861,9 @@ async function suiteCommand(args, io, deps = { run: executeRun }) {
13020
13861
  }
13021
13862
  const stores = await loadStores(storesPath, io);
13022
13863
  if (!stores) return 2;
13023
- const scenarios = await scan2(scenarioDir, trackers, loaded?.config.options ?? {}, io);
13864
+ const scenarios = await scan3(scenarioDir, trackers, loaded?.config.options ?? {}, io);
13024
13865
  if (!scenarios) return 2;
13866
+ if (args.consent) checkConsentMatrix(scenarios, args.consent);
13025
13867
  const undeclared = undeclaredVars(scenarios, args.vars);
13026
13868
  if (undeclared.length) {
13027
13869
  io.stderr(`--var ${undeclared.join(", ")} not declared in the vars of any scenario. --var only overrides declared variables.
@@ -13123,14 +13965,19 @@ ${hints.join(" ")}
13123
13965
  const startedAt = Date.now();
13124
13966
  const variants2 = args.variants.map((v) => v.name);
13125
13967
  const cells = [];
13968
+ const recordPaths = /* @__PURE__ */ new Map();
13969
+ const states = args.consent ?? [void 0];
13970
+ const combos = states.flatMap((state) => variants2.map((variant) => ({ state, variant })));
13126
13971
  const ordered = [...scenarios.filter((s) => !s.handoff), ...scenarios.filter((s) => s.handoff)];
13127
13972
  for (const s of ordered) {
13128
13973
  const seed = args.seed ?? s.parsed.options.seed ?? Math.floor(Math.random() * 2 ** 31);
13129
13974
  for (const { store, site: site2 } of targets) {
13130
13975
  const key = paymentKey(s.name, store);
13131
- const parsed = scenarioFor(s, store, args.vars, io);
13132
- for (const variant of variants2) {
13133
- const cell = { scenario: s.name, variant, labels: store ? { store: store.name } : {} };
13976
+ const scenarioOfStore = scenarioFor(s, store, args.vars, io);
13977
+ for (const { state, variant } of combos) {
13978
+ const parsed = state ? withConsent(scenarioOfStore, state) : scenarioOfStore;
13979
+ const skippedRules = state && state !== ownConsentState(scenarioOfStore) ? ruleCount(scenarioOfStore) : 0;
13980
+ const cell = { scenario: s.name, variant, labels: { ...store && { store: store.name }, ...state && { consent: state } } };
13134
13981
  if (s.handoff && !args.withHandoff) {
13135
13982
  cells.push({ ...cell, status: "skipped", exitCode: 0 });
13136
13983
  continue;
@@ -13139,7 +13986,7 @@ ${hints.join(" ")}
13139
13986
  cells.push({ ...cell, status: "skipped", exitCode: 0 });
13140
13987
  continue;
13141
13988
  }
13142
- io.stderr(`Running ${s.name}${store ? ` on ${store.name}` : ""} (${variant})
13989
+ io.stderr(`Running ${s.name}${store ? ` on ${store.name}` : ""}${state ? ` with consent ${state}` : ""} (${variant})
13143
13990
  `);
13144
13991
  const outcome = await deps.run(
13145
13992
  {
@@ -13150,6 +13997,7 @@ ${hints.join(" ")}
13150
13997
  out: dir,
13151
13998
  ...args.label !== void 0 && { label: args.label },
13152
13999
  ...store && { store: store.name },
14000
+ ...state && { consentCell: state },
13153
14001
  seed,
13154
14002
  headed: false,
13155
14003
  viewport: args.viewport,
@@ -13179,12 +14027,14 @@ ${hints.join(" ")}
13179
14027
  if (exitCode === 0) exitCode = 1;
13180
14028
  }
13181
14029
  }
13182
- cells.push({ ...cell, status, exitCode, ...failed && { failed }, ...outcome.path && { record: basename2(outcome.path) }, ...compared && { baseline: compared } });
14030
+ const done = { ...cell, status, exitCode, ...skippedRules > 0 && { rulesSkipped: skippedRules }, ...failed && { failed }, ...outcome.path && { record: basename2(outcome.path) }, ...compared && { baseline: compared } };
14031
+ if (outcome.path) recordPaths.set(done, outcome.path);
14032
+ cells.push(done);
13183
14033
  }
13184
14034
  }
13185
14035
  }
13186
14036
  const storeNames = stores.map((st) => st.name);
13187
- const position = (c) => (scenarios.findIndex((s) => s.name === c.scenario) * Math.max(storeNames.length, 1) + Math.max(storeNames.indexOf(c.labels.store ?? ""), 0)) * variants2.length + variants2.indexOf(c.variant);
14037
+ const position = (c) => ((scenarios.findIndex((s) => s.name === c.scenario) * Math.max(storeNames.length, 1) + Math.max(storeNames.indexOf(c.labels.store ?? ""), 0)) * states.length + Math.max(states.indexOf(c.labels.consent), 0)) * variants2.length + variants2.indexOf(c.variant);
13188
14038
  cells.sort((a, b) => position(a) - position(b));
13189
14039
  const listed = [...loaded?.defaultUsed ? [loaded.defaultUsed] : [], ...defaults];
13190
14040
  const manifest = {
@@ -13195,7 +14045,9 @@ ${hints.join(" ")}
13195
14045
  site: new URL(targets[0].site).origin,
13196
14046
  stores: stores.map((st) => ({ name: st.name, site: new URL(st.site).origin })),
13197
14047
  variants: variants2,
14048
+ ...args.consent && { consent: args.consent },
13198
14049
  cells,
14050
+ ...args.consent && { consentMatrix: await consentMatrixOf(cells, recordPaths) },
13199
14051
  diffs: await diffPairs(cells, variants2, storeNames, dir),
13200
14052
  exitCode: suiteExitCode(cells),
13201
14053
  ...listed.length > 0 && { defaults: listed }
@@ -13208,7 +14060,7 @@ ${hints.join(" ")}
13208
14060
  }
13209
14061
 
13210
14062
  // packages/cli/src/report/suite.ts
13211
- var recordKey = (scenario, variant, store) => JSON.stringify(store === void 0 ? [scenario, variant] : [scenario, variant, store]);
14063
+ var recordKey = (scenario, variant, store, consent) => JSON.stringify(consent !== void 0 ? [scenario, variant, store ?? null, consent] : store === void 0 ? [scenario, variant] : [scenario, variant, store]);
13212
14064
  function hostOf7(url) {
13213
14065
  try {
13214
14066
  return new URL(url).host;
@@ -13239,7 +14091,10 @@ function diffView(scenario, store, from, to, a, b) {
13239
14091
  flags: result.flags.filter((f) => !f.allowed).map((f) => ({ kind: f.kind, host: f.host, a: f.a, b: f.b }))
13240
14092
  };
13241
14093
  }
14094
+ var isConsentSuite = (manifest) => manifest.consent !== void 0 || manifest.cells.some((c) => c.labels?.consent !== void 0);
13242
14095
  function buildSuiteModel(manifest, records) {
14096
+ const consentSuite = isConsentSuite(manifest);
14097
+ const states = consentSuite ? [.../* @__PURE__ */ new Set([...manifest.consent ?? [], ...manifest.cells.flatMap((c) => c.labels?.consent === void 0 ? [] : [c.labels.consent])])] : [void 0];
13243
14098
  const warnings = [];
13244
14099
  const names = [...new Set(manifest.cells.map((c) => c.scenario))];
13245
14100
  const storeNames = manifest.stores.map((s) => s.name);
@@ -13247,20 +14102,38 @@ function buildSuiteModel(manifest, records) {
13247
14102
  const scenarios = names.map((name) => ({
13248
14103
  name,
13249
14104
  cells: storeAxis.flatMap(
13250
- (store) => manifest.variants.flatMap((variant) => {
13251
- const cell = manifest.cells.find((c) => c.scenario === name && c.labels?.store === store && c.variant === variant);
13252
- if (!cell) return [];
13253
- const label = `${name}${store === void 0 ? "" : ` on ${store}`} (${variant})`;
13254
- const loaded = records.get(recordKey(name, variant, store));
13255
- if (!loaded && cell.status !== "skipped") warnings.push(`${label}: no record, so the run is not in this report`);
13256
- if (loaded?.truncatedAtLine) warnings.push(`${label}: record is truncated at line ${loaded.truncatedAtLine}, so later records are missing from this report`);
13257
- return [{ ...store !== void 0 && { store }, variant, status: cell.status, exitCode: cell.exitCode, ...cell.failed && { failed: cell.failed }, ...cell.baseline && { baseline: cell.baseline }, model: loaded && buildReportModel(loaded) }];
13258
- })
14105
+ (store) => manifest.variants.flatMap(
14106
+ (variant) => states.flatMap((consent) => {
14107
+ const cell = manifest.cells.find((c) => c.scenario === name && c.labels?.store === store && c.variant === variant && c.labels?.consent === consent);
14108
+ if (!cell) return [];
14109
+ const label = `${name}${store === void 0 ? "" : ` on ${store}`} (${variant}${consent === void 0 ? "" : `, consent ${consent}`})`;
14110
+ let loaded = records.get(recordKey(name, variant, store, consent));
14111
+ if (!loaded && cell.status !== "skipped") warnings.push(`${label}: no record, so the run is not in this report`);
14112
+ if (loaded && consent !== void 0 && loaded.run.consentCell !== consent) {
14113
+ warnings.push(`${label}: the record ${loaded.run.consentCell === void 0 ? "names no consent state" : `is for consent state ${loaded.run.consentCell}`}, so it is not shown for this cell`);
14114
+ loaded = void 0;
14115
+ }
14116
+ if (loaded?.truncatedAtLine) warnings.push(`${label}: record is truncated at line ${loaded.truncatedAtLine}, so later records are missing from this report`);
14117
+ return [
14118
+ {
14119
+ ...store !== void 0 && { store },
14120
+ ...consent !== void 0 && { consent },
14121
+ variant,
14122
+ status: cell.status,
14123
+ exitCode: cell.exitCode,
14124
+ ...cell.failed && { failed: cell.failed },
14125
+ ...cell.rulesSkipped !== void 0 && { rulesSkipped: cell.rulesSkipped },
14126
+ ...cell.baseline && { baseline: cell.baseline },
14127
+ model: loaded && buildReportModel(loaded)
14128
+ }
14129
+ ];
14130
+ })
14131
+ )
13259
14132
  )
13260
14133
  }));
13261
14134
  const [first, ...others] = manifest.variants;
13262
14135
  const diffs = [];
13263
- for (const name of names) {
14136
+ for (const name of consentSuite ? [] : names) {
13264
14137
  for (const store of storeAxis) {
13265
14138
  const a = records.get(recordKey(name, first, store));
13266
14139
  for (const to of others) {
@@ -13281,7 +14154,8 @@ function buildSuiteModel(manifest, records) {
13281
14154
  },
13282
14155
  warnings,
13283
14156
  scenarios,
13284
- diffs
14157
+ diffs,
14158
+ ...consentSuite && { consent: { states, matrix: manifest.consentMatrix ?? [] } }
13285
14159
  };
13286
14160
  }
13287
14161
  function isFailedField(value) {
@@ -13304,12 +14178,16 @@ function isBaselineField(value) {
13304
14178
  const b = value;
13305
14179
  return typeof b === "object" && b !== null && typeof b.file === "string" && typeof b.drift === "boolean" && [b.added, b.removed, b.countChanges].every((n) => typeof n === "number");
13306
14180
  }
14181
+ function isMatrixEntry(value) {
14182
+ const e = value;
14183
+ return typeof e === "object" && e !== null && typeof e.scenario === "string" && (e.store === void 0 || typeof e.store === "string") && Array.isArray(e.vendors);
14184
+ }
13307
14185
  function isManifest(value) {
13308
14186
  if (typeof value !== "object" || value === null) return false;
13309
14187
  const m = value;
13310
- return (m.suiteSchemaVersion === 1 || m.suiteSchemaVersion === 2 || m.suiteSchemaVersion === 3) && typeof m.id === "string" && (m.label === void 0 || typeof m.label === "string") && typeof m.startedAt === "number" && Number.isFinite(m.startedAt) && typeof m.site === "string" && typeof m.exitCode === "number" && (m.suiteSchemaVersion === 1 || isStoreList(m.stores)) && Array.isArray(m.variants) && m.variants.every((v) => typeof v === "string") && Array.isArray(m.cells) && m.cells.every((c) => {
14188
+ return (m.suiteSchemaVersion === 1 || m.suiteSchemaVersion === 2 || m.suiteSchemaVersion === 3) && typeof m.id === "string" && (m.label === void 0 || typeof m.label === "string") && typeof m.startedAt === "number" && Number.isFinite(m.startedAt) && typeof m.site === "string" && typeof m.exitCode === "number" && (m.suiteSchemaVersion === 1 || isStoreList(m.stores)) && Array.isArray(m.variants) && m.variants.every((v) => typeof v === "string") && (m.consentMatrix === void 0 || Array.isArray(m.consentMatrix) && m.consentMatrix.every(isMatrixEntry)) && Array.isArray(m.cells) && m.cells.every((c) => {
13311
14189
  const cell = c;
13312
- return typeof cell === "object" && cell !== null && typeof cell.scenario === "string" && typeof cell.variant === "string" && typeof cell.status === "string" && typeof cell.exitCode === "number" && isFailedField(cell.failed) && isLabels(cell.labels) && isBaselineField(cell.baseline);
14190
+ return typeof cell === "object" && cell !== null && typeof cell.scenario === "string" && typeof cell.variant === "string" && typeof cell.status === "string" && typeof cell.exitCode === "number" && isFailedField(cell.failed) && isLabels(cell.labels) && isBaselineField(cell.baseline) && (cell.rulesSkipped === void 0 || Number.isInteger(cell.rulesSkipped) && cell.rulesSkipped >= 0);
13313
14191
  });
13314
14192
  }
13315
14193
  async function hasManifest(dir) {
@@ -13346,7 +14224,7 @@ async function loadSuite(dir) {
13346
14224
  for (const cell of manifest.cells) {
13347
14225
  const name = cell.record;
13348
14226
  if (typeof name !== "string" || name !== basename3(name)) continue;
13349
- records.set(recordKey(cell.scenario, cell.variant, cell.labels.store), await readRun(join14(dir, name)).catch(() => void 0));
14227
+ records.set(recordKey(cell.scenario, cell.variant, cell.labels.store, cell.labels.consent), await readRun(join14(dir, name)).catch(() => void 0));
13350
14228
  }
13351
14229
  return { manifest, records };
13352
14230
  }
@@ -13397,10 +14275,90 @@ function suiteTitle(h) {
13397
14275
  const where2 = h.stores.length ? ` on ${h.stores.join(", ")}` : h.host ? ` on ${h.host}` : "";
13398
14276
  return `Tagreeve suite: ${h.variants.join(" vs ")}${where2}, ${h.startedAt.slice(0, 10)}`;
13399
14277
  }
14278
+ var AUDIT_INTRO = "This report shows what was sent and flags likely problems. People decide what is allowed. A pass means no planted value was found in the searched forms. The searched parts are the URL, the body and decoded fields. Request headers, including Referer and Cookie, were not searched.";
14279
+ var VERDICT_CLASS2 = { PASS: "full", WARN: "ping", FAIL: "leak" };
14280
+ function cellVerdict(status) {
14281
+ return status === "error" ? "ERROR (did not finish)" : status.toUpperCase();
14282
+ }
14283
+ function auditColumn(c) {
14284
+ const verdict = cellVerdict(c.status);
14285
+ const head = `<h4>${escapeHtml(c.consent ?? "")}</h4><p class="verdict m-${VERDICT_CLASS2[verdict] ?? "nothing"}"><strong>${escapeHtml(verdict)}</strong></p>`;
14286
+ const skipped = c.rulesSkipped === void 0 ? "" : `<p class="empty">${c.rulesSkipped} ${c.rulesSkipped === 1 ? "rule" : "rules"} skipped: the scenario's own rules run in their own state.</p>`;
14287
+ const model = c.model;
14288
+ if (!model) return `${head}${skipped}<p class="empty">${c.status === "skipped" ? "Skipped." : "No record to show."}</p>`;
14289
+ const setup = model.expectations.find((e) => e.text === "builtin: consentModeSetup");
14290
+ const problems = model.expectations.filter((e) => e.status !== "PASS" && e !== setup);
14291
+ const list3 = problems.length ? `<ul class="results">${problems.map((e) => `<li class="s-${e.status.toLowerCase().replace(" ", "-")}"><span class="status">${escapeHtml(e.status)}</span><code>${escapeHtml(e.text)}</code>${e.note ? `<span class="note">${escapeHtml(e.note)}</span>` : ""}</li>`).join("")}</ul>` : '<p class="empty">No rule or built-in check needs attention.</p>';
14292
+ const setupLine = setup ? `<p>consentModeSetup: <strong>${escapeHtml(setup.status)}</strong>${setup.note ? ` <span class="empty">${escapeHtml(setup.note)}</span>` : ""}</p>` : '<p class="empty">consentModeSetup: no result in this record</p>';
14293
+ const routes2 = model.routes;
14294
+ const routeList = !routes2 ? '<p class="empty">The run had no canaries, so no identifier route was searched.</p>' : routes2.rows.length === 0 ? '<p class="empty">No planted value was found in a request to a non-first-party host.</p>' : `<ul class="results">${routes2.rows.map((r) => `<li class="s-${r.verdict.toLowerCase()}"><span class="status">${r.verdict}</span><code>${escapeHtml(r.host)}</code>${escapeHtml(r.line)}<span class="note">epoch at sink: ${escapeHtml(r.epoch)}</span></li>`).join("")}</ul>`;
14295
+ const search = routes2?.search;
14296
+ const reasons = search?.reasons.length ? ` (${search.reasons.map((r) => `${r.count} ${r.reason}`).join(", ")})` : "";
14297
+ const searched = [
14298
+ ...search?.forms ? [`Forms searched: ${search.forms}.`] : [],
14299
+ "Parts searched: URL, body and decoded fields.",
14300
+ "Parts not searched: request headers, including Referer and Cookie.",
14301
+ ...search ? [...search.requests === void 0 ? [] : [`Requests searched: ${search.requests}.`], `Requests skipped: ${search.skipped}${reasons}.`] : ["No canaries in this run, so no request was searched."]
14302
+ ];
14303
+ return `${head}${skipped}<h5>Rules and built-in checks</h5>${list3}${setupLine}<h5>Identifier routes</h5>${routeList}<h5>Searched and skipped</h5><ul class="fields">${searched.map((i) => `<li>${escapeHtml(i)}</li>`).join("")}</ul>`;
14304
+ }
14305
+ function matrixTable(entry, states) {
14306
+ const head = states.map((s) => `<th scope="col">${escapeHtml(s)}</th>`).join("");
14307
+ const rows = entry.vendors.map((v) => {
14308
+ const counts = states.map((s) => {
14309
+ const hits = v.states[s]?.hits;
14310
+ return `<td>${typeof hits === "number" ? hits : "-"}</td>`;
14311
+ });
14312
+ return `<tr><th scope="row">${escapeHtml(v.vendor)}</th>${counts.join("")}</tr>`;
14313
+ }).join("");
14314
+ return `<div class="scroll"><table class="matrix"><thead><tr><th scope="col">Vendor (hits)</th>${head}</tr></thead><tbody>${rows}</tbody></table></div>`;
14315
+ }
14316
+ function consentAudit(model) {
14317
+ const { states, matrix } = model.consent;
14318
+ const groups = model.scenarios.flatMap((s) => [...new Set(s.cells.map((c) => c.store))].map((store) => ({ name: s.name, store, cells: s.cells.filter((c) => c.store === store) }))).map((g) => {
14319
+ const where2 = g.store === void 0 ? g.name : `${g.name} on ${g.store}`;
14320
+ const entry = matrix.find((e) => e.scenario === g.name && e.store === g.store);
14321
+ const table = entry ? matrixTable(entry, states) : "";
14322
+ const variants2 = [...new Set(g.cells.map((c) => c.variant))].map((variant) => {
14323
+ const columns = g.cells.filter((c) => c.variant === variant);
14324
+ const grid = `<div style="display:grid;grid-template-columns:repeat(${columns.length},minmax(220px,1fr));gap:12px;overflow-x:auto">${columns.map((c) => `<section class="audit-col" data-state="${escapeHtml(c.consent ?? "")}">${auditColumn(c)}</section>`).join("")}</div>`;
14325
+ return `${g.cells.some((c) => c.variant !== variant) ? `<h4>${escapeHtml(variant)}</h4>` : ""}${grid}`;
14326
+ });
14327
+ return `<h3>${escapeHtml(where2)}</h3>${table}${variants2.join("")}`;
14328
+ });
14329
+ return `<section class="consent-audit"><h2>Consent audit</h2><p class="verdict">${escapeHtml(AUDIT_INTRO)}</p>${groups.join("")}</section>`;
14330
+ }
14331
+ function consentRuns(model) {
14332
+ return model.scenarios.map((s) => {
14333
+ const cells = s.cells.map((c) => {
14334
+ const where2 = `${s.name}${c.store === void 0 ? "" : ` on ${c.store}`}, ${c.variant}, consent ${c.consent ?? ""}`;
14335
+ const title = `<h3>${escapeHtml(where2)}: ${escapeHtml(cellVerdict(c.status))}</h3>`;
14336
+ if (!c.model) return `${title}<p class="empty">${c.status === "skipped" ? "Skipped." : "No record to show."}</p>`;
14337
+ return `${title}${definitionList(runHeader(c.model.header))}${runSections(c.model, "h4")}`;
14338
+ }).join("");
14339
+ return `<section><h2>Runs: ${escapeHtml(s.name)}</h2>${cells}</section>`;
14340
+ }).join("");
14341
+ }
13400
14342
  function renderSuiteReport(model) {
13401
14343
  const h = model.header;
13402
14344
  const title = suiteTitle(h);
13403
14345
  const warnings = model.warnings.map((w) => `<p class="warn-box">Warning: ${escapeHtml(w)}</p>`).join("");
14346
+ if (model.consent) {
14347
+ return page(`<h1>${escapeHtml(title)}</h1>
14348
+ ${definitionList([
14349
+ ["Suite", h.id],
14350
+ ...h.label === void 0 ? [] : [["Label", h.label]],
14351
+ ["Started", h.startedAt],
14352
+ ["Site host", h.host],
14353
+ ...h.stores.length ? [["Stores", h.stores.join(", ")]] : [],
14354
+ ["Variants", h.variants.join(", ")],
14355
+ ["Consent states", model.consent.states.join(", ")],
14356
+ ["Exit code", String(Number(h.exitCode))]
14357
+ ])}
14358
+ ${warnings}
14359
+ ${consentAudit(model)}
14360
+ ${consentRuns(model)}`, title);
14361
+ }
13404
14362
  const scenarios = model.scenarios.map((s) => {
13405
14363
  const cells = s.cells.map((c) => {
13406
14364
  const where2 = c.store === void 0 ? `${s.name} (${c.variant})` : `${s.name} on ${c.store}, ${c.variant}`;