tagreeve 0.6.0-rc.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -272,26 +272,26 @@ var US = {
272
272
  locale: [en_US, en, base],
273
273
  zip: (faker) => faker.location.zipCode("#####"),
274
274
  phone: (faker) => `+1${faker.helpers.arrayElement(US_AREA_CODES)}5550${faker.number.int({ min: 100, max: 199 })}`,
275
- nationalDigits: (digits) => digits.slice(1)
275
+ nationalDigits: (digits2) => digits2.slice(1)
276
276
  };
277
277
  var SE = {
278
278
  locale: [sv, en, base],
279
279
  zip: (faker) => String(faker.number.int({ min: 100, max: 984 })) + " " + faker.string.numeric(2),
280
280
  phone: (faker) => `+4670174${String(faker.number.int({ min: 605, max: 699 })).padStart(4, "0")}`,
281
- nationalDigits: (digits) => "0" + digits.slice(2)
281
+ nationalDigits: (digits2) => "0" + digits2.slice(2)
282
282
  };
283
283
  var GB = {
284
284
  locale: [en_GB, en, base],
285
285
  // The en_GB locale patterns can give shapes such as "SW54 27L".
286
286
  zip: (faker) => faker.helpers.fromRegExp("[A-PR-UWYZ][A-HK-Y]?[0-9] [0-9][ABD-HJLNP-UW-Z]{2}"),
287
287
  phone: (faker) => `+447700900${String(faker.number.int({ min: 0, max: 999 })).padStart(3, "0")}`,
288
- nationalDigits: (digits) => "0" + digits.slice(2)
288
+ nationalDigits: (digits2) => "0" + digits2.slice(2)
289
289
  };
290
290
  var DE = {
291
291
  locale: [de, en, base],
292
292
  zip: (faker) => faker.location.zipCode(),
293
293
  phone: (faker) => `+493023125${String(faker.number.int({ min: 0, max: 999 })).padStart(3, "0")}`,
294
- nationalDigits: (digits) => "0" + digits.slice(2)
294
+ nationalDigits: (digits2) => "0" + digits2.slice(2)
295
295
  };
296
296
  var COUNTRIES = { US, SE, GB, DE };
297
297
  var FICTIONAL_PHONE_HINT = {
@@ -564,8 +564,8 @@ function* candidates(text2) {
564
564
  }
565
565
  }
566
566
  for (const m of variant.match(PHONE) ?? []) {
567
- const digits = m.replace(/\D/g, "");
568
- if (digits.length < 8 || digits.length > 15) continue;
567
+ const digits2 = m.replace(/\D/g, "");
568
+ if (digits2.length < 8 || digits2.length > 15) continue;
569
569
  if (/^\+\d+\+/.test(m) && !/^\+\d{1,3}\+/.test(m)) continue;
570
570
  yield { kind: "phone", value: m, variant, index: 0 };
571
571
  }
@@ -592,8 +592,8 @@ function scan(text2, identity, options = {}) {
592
592
  add2("email", c.value);
593
593
  if (c.alternate) add2("email", c.alternate);
594
594
  } else if (c.kind === "phone") {
595
- const digits = c.value.replace(/\D/g, "");
596
- if (!digits.includes(own.phoneDigits) && !digits.includes(own.nationalDigits) && !own.extraPhones.includes(digits)) add2("phone", c.value);
595
+ const digits2 = c.value.replace(/\D/g, "");
596
+ if (!digits2.includes(own.phoneDigits) && !digits2.includes(own.nationalDigits) && !own.extraPhones.includes(digits2)) add2("phone", c.value);
597
597
  } else if (!own.hashes.has(c.value) && !options.stableHashes?.has(c.value) && !isNonPersonalKey(c.variant, c.index)) {
598
598
  add2("hash", c.value);
599
599
  }
@@ -680,8 +680,8 @@ var DIGEST_TOKEN = /^[A-Za-z0-9_-]{22,}$/;
680
680
  var LONG_DIGITS = /\d{6,}/;
681
681
  var BODY_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
682
682
  function mostlyDigits(segment) {
683
- const digits = segment.replace(/\D/g, "").length;
684
- return digits >= 6 && digits * 2 >= segment.length;
683
+ const digits2 = segment.replace(/\D/g, "").length;
684
+ return digits2 >= 6 && digits2 * 2 >= segment.length;
685
685
  }
686
686
  function looksLikeValueToken(segment) {
687
687
  if (segment.length > 64) return true;
@@ -917,6 +917,10 @@ function gcdSignals(gcd) {
917
917
  });
918
918
  return out;
919
919
  }
920
+ function gcdLetters(gcd) {
921
+ if (!gcdSignals(gcd)) return void 0;
922
+ return GCD_SIGNALS.map((_, i) => gcd[2 + 2 * i] in GCD_LETTERS ? gcd[2 + 2 * i] : "?");
923
+ }
920
924
  function gcdValue(signal) {
921
925
  if (signal.notSet) return "unknown";
922
926
  return signal.update !== "unknown" ? signal.update : signal.default;
@@ -1857,6 +1861,7 @@ var VENDOR_KEYS = /* @__PURE__ */ new Set(["vendor", "event", "page", "transport
1857
1861
  var GROUP_KEYS = ["consent", "ids", "params", "identity", "body"];
1858
1862
  var COOKIE_RULE_KEYS = ["cookie", "before", "in", "after", "from"];
1859
1863
  var TAG_RULE_KEYS = ["tag", "count", "after", "from"];
1864
+ var TAG_STATUSES = ["success", "failure", "exception", "timeout"];
1860
1865
  var TAG_SELECTOR_KEYS = ["id", "name", "container", "event", "status", "side"];
1861
1866
  var MAX_TAG_TEXT = 200;
1862
1867
  var BODY_KEYS = ["has", "only", "ignore"];
@@ -1952,8 +1957,8 @@ function parseOptions(raw, path, fail, { keys = OPTION_KEYS, echo = true } = {})
1952
1957
  } else if (k === "serverHosts") {
1953
1958
  if (!Array.isArray(v) || v.length === 0 || !v.every(isServerHostPattern)) fail(p, `must be a non-empty list of hosts${HOST_HINT}`);
1954
1959
  else {
1955
- const bad = v.find((host) => !isSpecificServerHost(host));
1956
- if (bad !== void 0) fail(p, `${echo ? `"${bad}"` : "a host in the list"} is a vendor host or a wildcard on a public suffix. List the server container's own host, such as sgtm.example.com or *.example.com`);
1960
+ const bad2 = v.find((host) => !isSpecificServerHost(host));
1961
+ if (bad2 !== void 0) fail(p, `${echo ? `"${bad2}"` : "a host in the list"} is a vendor host or a wildcard on a public suffix. List the server container's own host, such as sgtm.example.com or *.example.com`);
1957
1962
  else options.serverHosts = v;
1958
1963
  }
1959
1964
  } else if (k === "viewport") {
@@ -2275,10 +2280,15 @@ function parseScenario(text2, extraVendorKeys = []) {
2275
2280
  else if (typeof value === "string" && /^\s*\d/.test(value)) fail([...path, kind], `"${value}" is not a duration such as 4s, 500ms or 2m`);
2276
2281
  else if (typeof value === "string" && value.trim()) add2({ kind, value: { selector: value } });
2277
2282
  else if (isMap(value) && "url" in value) {
2278
- if (Object.keys(value).length > 1) fail([...path, kind], "url cannot be combined with other keys");
2283
+ if (Object.keys(value).some((k) => k !== "url" && k !== "timeout")) fail([...path, kind], "url only takes timeout");
2279
2284
  else {
2280
2285
  const url = urlMatcher(value.url, [...path, kind, "url"]);
2281
- if (url) add2({ kind, value: { url } });
2286
+ let timeout;
2287
+ if ("timeout" in value) {
2288
+ timeout = parseDuration(value.timeout);
2289
+ if (timeout === void 0) fail([...path, kind, "timeout"], "must be a duration such as 90s or 2m");
2290
+ }
2291
+ if (url && (!("timeout" in value) || timeout !== void 0)) add2({ kind, value: timeout === void 0 ? { url } : { url, timeout } });
2282
2292
  }
2283
2293
  } else if (isMap(value)) {
2284
2294
  const v = locator();
@@ -2332,6 +2342,7 @@ function parseScenario(text2, extraVendorKeys = []) {
2332
2342
  } else if (key === "status") {
2333
2343
  const items = Array.isArray(raw2) ? raw2 : [raw2];
2334
2344
  if (items.length === 0 || !items.every((x) => typeof x === "string" && x && x.length <= MAX_FIELD_NAME)) fail(p, "must be a status or a list of statuses");
2345
+ else if (!items.every((x) => TAG_STATUSES.includes(x))) fail(p, `must be one of ${TAG_STATUSES.join(", ")}`);
2335
2346
  else tag.status = items;
2336
2347
  } else if (key === "side") {
2337
2348
  if (raw2 === "web" || raw2 === "server") tag.side = raw2;
@@ -2362,9 +2373,9 @@ function parseScenario(text2, extraVendorKeys = []) {
2362
2373
  return void 0;
2363
2374
  }
2364
2375
  const out = items;
2365
- const bad = allowed ? out.find((x) => !allowed.includes(x)) : void 0;
2366
- if (bad !== void 0) {
2367
- fail([...path, key], `"${bad}" is not valid, expected one of ${allowed.join(", ")}`);
2376
+ const bad2 = allowed ? out.find((x) => !allowed.includes(x)) : void 0;
2377
+ if (bad2 !== void 0) {
2378
+ fail([...path, key], `"${bad2}" is not valid, expected one of ${allowed.join(", ")}`);
2368
2379
  return void 0;
2369
2380
  }
2370
2381
  return out;
@@ -2499,20 +2510,20 @@ function looksLikeRealData(value) {
2499
2510
  if (email) return RESERVED_EMAIL_DOMAIN.test(email[1]) ? void 0 : "email";
2500
2511
  const text2 = value.trim();
2501
2512
  if (!PHONE_SHAPE.test(text2)) return void 0;
2502
- const digits = text2.replace(/\D/g, "");
2503
- const international = digits.length > 10 || text2.startsWith("+");
2504
- const nationalUs = !international && /^\d{3}55501\d\d$/.test(digits);
2505
- return nationalUs || FICTIONAL_PHONE.some((range) => range.test(digits)) ? void 0 : "phone";
2513
+ const digits2 = text2.replace(/\D/g, "");
2514
+ const international = digits2.length > 10 || text2.startsWith("+");
2515
+ const nationalUs = !international && /^\d{3}55501\d\d$/.test(digits2);
2516
+ return nationalUs || FICTIONAL_PHONE.some((range) => range.test(digits2)) ? void 0 : "phone";
2506
2517
  }
2507
2518
  var REAL_MOBILE_PREFIX = { DE: /^49(?:15|16|17)/, GB: /^447/, SE: /^467/ };
2508
2519
  var DIAL_CODE_COUNTRY = [["49", "DE"], ["46", "SE"], ["44", "GB"], ["1", "US"]];
2509
2520
  function phoneWarning(value, declaredCountry) {
2510
- const digits = value.replace(/\D/g, "");
2521
+ const digits2 = value.replace(/\D/g, "");
2511
2522
  const international = value.trim().startsWith("+");
2512
- const fromDialCode = international ? DIAL_CODE_COUNTRY.find(([code]) => digits.startsWith(code))?.[1] : void 0;
2523
+ const fromDialCode = international ? DIAL_CODE_COUNTRY.find(([code]) => digits2.startsWith(code))?.[1] : void 0;
2513
2524
  const country = fromDialCode ?? (international ? void 0 : declaredCountry?.toUpperCase() ?? "US");
2514
2525
  const reasons = ["it is not in a fictional range"];
2515
- if (country && REAL_MOBILE_PREFIX[country]?.test(digits)) reasons.push("its mobile prefix is a real one");
2526
+ if (country && REAL_MOBILE_PREFIX[country]?.test(digits2)) reasons.push("its mobile prefix is a real one");
2516
2527
  const hint = country && FICTIONAL_PHONE_HINT[country];
2517
2528
  const range = hint ? `use ${hint}` : "no fictional range is known for it";
2518
2529
  return `looks like a real phone (${reasons.join(" and ")}${country ? ` for ${country}` : ""}); ${range}`;
@@ -2527,23 +2538,37 @@ var CONSENT_MODE_URL = "https://developers.google.com/tag-platform/security/guid
2527
2538
  var GOOGLE_VENDORS = /* @__PURE__ */ new Set(["ga4", "google-ads"]);
2528
2539
  var TAG_ID = /^[A-Za-z]{1,3}-[A-Za-z0-9]{4,20}$/;
2529
2540
  var MAX_LISTED = 5;
2541
+ var MAX_LETTER_SETS = 3;
2530
2542
  function tagId(hit) {
2531
- const tid = hit.params.tid ?? (hit.params.conversionId ? `AW-${hit.params.conversionId}` : void 0);
2543
+ const conversionId = hit.params.conversionId;
2544
+ const tid = hit.vendor === "ga4" ? hit.params.tid : conversionId && /^\d+$/.test(conversionId) ? `AW-${conversionId}` : void 0;
2532
2545
  return tid && TAG_ID.test(tid) ? tid : "(no tag ID)";
2533
2546
  }
2534
2547
  function list(names) {
2535
2548
  return names.length < 2 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
2536
2549
  }
2550
+ function lettersNote(sets) {
2551
+ return [...sets].slice(0, MAX_LISTED).map(([tid, letters]) => `${tid} ${[...letters].slice(0, MAX_LETTER_SETS).join(", ")}`).join("; ");
2552
+ }
2537
2553
  function consentModeSetup(hits, dataLayer) {
2538
2554
  const google = hits.filter((h) => GOOGLE_VENDORS.has(h.vendor));
2539
2555
  if (google.length === 0) return { pass: true, evidence: [], message: "Expected Consent Mode signals to be set on Google hits, found no Google hits." };
2540
2556
  const unset = /* @__PURE__ */ new Map();
2541
2557
  const v1Only = /* @__PURE__ */ new Set();
2558
+ const letterSets = /* @__PURE__ */ new Map();
2542
2559
  const evidence = [];
2560
+ let noGcd = 0;
2543
2561
  let showsDefault = false;
2544
2562
  for (const hit of google) {
2545
2563
  const signals = gcdSignals(hit.consent.raw.gcd);
2546
- if (!signals) continue;
2564
+ if (!signals) {
2565
+ noGcd++;
2566
+ continue;
2567
+ }
2568
+ const tid = tagId(hit);
2569
+ const set = letterSets.get(tid) ?? /* @__PURE__ */ new Set();
2570
+ set.add(gcdLetters(hit.consent.raw.gcd).join(""));
2571
+ letterSets.set(tid, set);
2547
2572
  const hasDefault = GCD_SIGNALS.some((n) => {
2548
2573
  const s = signals[n];
2549
2574
  return !s.notSet && s.default !== "unknown";
@@ -2551,7 +2576,6 @@ function consentModeSetup(hits, dataLayer) {
2551
2576
  if (hasDefault) showsDefault = true;
2552
2577
  const missing = GCD_SIGNALS.filter((n) => signals[n].notSet);
2553
2578
  if (missing.length === 0) continue;
2554
- const tid = tagId(hit);
2555
2579
  evidence.push(hit.id);
2556
2580
  const names = unset.get(tid) ?? /* @__PURE__ */ new Set();
2557
2581
  for (const n of missing) names.add(n);
@@ -2559,25 +2583,30 @@ function consentModeSetup(hits, dataLayer) {
2559
2583
  const v1Default = [signals.ad_storage, signals.analytics_storage].every((s) => !s.notSet && s.default !== "unknown");
2560
2584
  if (v1Default && signals.ad_user_data.notSet && signals.ad_personalization.notSet) v1Only.add(tid);
2561
2585
  }
2586
+ if (noGcd === google.length) {
2587
+ return { pass: true, evidence: [], message: "Expected Consent Mode signals to be set on Google hits, but no Google hit carried gcd, so the setup could not be read." };
2588
+ }
2589
+ const missingNote = noGcd > 0 ? ` ${noGcd} Google hit${noGcd === 1 ? "" : "s"} carried no gcd.` : "";
2562
2590
  if (unset.size > 0) {
2563
2591
  const groups = [...unset].map(([tid, names]) => {
2564
2592
  const ordered = GCD_SIGNALS.filter((n) => names.has(n));
2565
2593
  const note = v1Only.has(tid) ? " (a default for ad_storage and analytics_storage only, without the two v2 signals)" : "";
2566
- return `Google tag ${tid} never set ${list(ordered)}${note}`;
2594
+ const letters = [...letterSets.get(tid) ?? []].slice(0, MAX_LETTER_SETS).join(", ");
2595
+ return `Google tag ${tid} never set ${list(ordered)}${note} (gcd letters: ${letters})`;
2567
2596
  });
2568
2597
  const shown2 = groups.slice(0, MAX_LISTED).join("; ");
2569
2598
  const more = groups.length > MAX_LISTED ? `; and ${groups.length - MAX_LISTED} more` : "";
2570
2599
  return {
2571
2600
  pass: false,
2572
2601
  evidence,
2573
- message: `${evidence.length} Google hit${evidence.length === 1 ? "" : "s"} show a Consent Mode signal that was never set: ${shown2}${more}. See ${CONSENT_MODE_URL}`
2602
+ message: `${evidence.length} Google hit${evidence.length === 1 ? "" : "s"} show a Consent Mode signal that was never set: ${shown2}${more}.${missingNote} See ${CONSENT_MODE_URL}`
2574
2603
  };
2575
2604
  }
2576
2605
  const pushed = dataLayer.some((e) => e.isConsentCommand && e.args[0] === "consent" && e.args[1] === "default");
2577
2606
  if (showsDefault && !pushed) {
2578
- return { pass: true, evidence: [], message: "Consent Mode signals are set on every Google hit; default set outside the dataLayer (template API, TCF or other)." };
2607
+ return { pass: true, evidence: [], message: `Consent Mode signals are set on every Google hit${noGcd > 0 ? " that carried gcd" : ""}; default set outside the dataLayer (template API, TCF or other) (gcd letters: ${lettersNote(letterSets)}).${missingNote}` };
2579
2608
  }
2580
- return { pass: true, evidence: [], message: "Expected Consent Mode signals to be set on Google hits, found every signal set." };
2609
+ return { pass: true, evidence: [], message: `Expected Consent Mode signals to be set on Google hits, found every signal set (gcd letters: ${lettersNote(letterSets)}).${missingNote}` };
2581
2610
  }
2582
2611
 
2583
2612
  // packages/expect/src/tags.ts
@@ -2585,11 +2614,12 @@ var TAG_REPORTER_HINT = "tagreeve template web --json";
2585
2614
  var MAX_LISTED2 = 5;
2586
2615
  var STATUS_WORD = /^[a-z_]{1,20}$/;
2587
2616
  var ID_WORD = /^[\w.-]{1,40}$/;
2588
- var NAME_SEPARATORS = /[\s/=:?&#|,;]+/;
2617
+ var COARSE_SEPARATORS = /[\s/=:?&#|,;]+/;
2618
+ var NAME_SEPARATORS = /[\s/=:?&#|,;._+()[\]{}<>'"`]+/;
2589
2619
  function maskTagName(name) {
2590
2620
  const kinds = valueKinds(name);
2591
2621
  if (kinds.has("email") || kinds.has("phone")) return OTHER_NAME;
2592
- return name.split(NAME_SEPARATORS).some((part) => isValueSegment(part)) ? OTHER_NAME : name;
2622
+ return [...name.split(COARSE_SEPARATORS), ...name.split(NAME_SEPARATORS)].some((part) => isValueSegment(part)) ? OTHER_NAME : name;
2593
2623
  }
2594
2624
  function maskTagId(id) {
2595
2625
  return ID_WORD.test(id) ? id : OTHER_NAME;
@@ -3328,7 +3358,7 @@ function checkHashes(hits, ctx) {
3328
3358
  const uncheckedFields = /* @__PURE__ */ new Set();
3329
3359
  for (const hit of hits) {
3330
3360
  let seen = false;
3331
- let bad = false;
3361
+ let bad2 = false;
3332
3362
  let raw = false;
3333
3363
  let plainHit = false;
3334
3364
  if (hit.vendor === "meta") {
@@ -3350,7 +3380,7 @@ function checkHashes(hits, ctx) {
3350
3380
  matchedFields.add(label);
3351
3381
  continue;
3352
3382
  }
3353
- bad = true;
3383
+ bad2 = true;
3354
3384
  if (verdict === "unhashed") {
3355
3385
  raw = true;
3356
3386
  unhashedFields.add(label);
@@ -3360,7 +3390,7 @@ function checkHashes(hits, ctx) {
3360
3390
  }
3361
3391
  }
3362
3392
  if (seen) withHash.push(hit.id);
3363
- if (bad) wrong.push(hit.id);
3393
+ if (bad2) wrong.push(hit.id);
3364
3394
  if (raw) unhashed.push(hit.id);
3365
3395
  if (plainHit) plainCapi.push(hit.id);
3366
3396
  }
@@ -3808,16 +3838,51 @@ function bodyTexts(headers, body) {
3808
3838
  function isEdgeShift(a, b, bodies) {
3809
3839
  const [short, long] = a.length <= b.length ? [a, b] : [b, a];
3810
3840
  if (!long.includes(short)) return false;
3811
- return bodies.every((raw) => {
3812
- const text2 = raw.replace(/\[\]|%5B%5D/gi, "");
3813
- const covered = [];
3814
- for (let i = text2.indexOf(long); i >= 0; i = text2.indexOf(long, i + 1)) covered.push([i, i + long.length]);
3815
- for (let i = text2.indexOf(short); i >= 0; i = text2.indexOf(short, i + 1)) {
3816
- if (!covered.some(([from, to]) => i >= from && i + short.length <= to)) return false;
3841
+ let sawLong = false;
3842
+ const ok = bodies.every(
3843
+ (raw) => readingForms(raw.replace(/\[\]|%5B%5D/gi, "")).every((text2) => {
3844
+ if (!text2.includes(long)) return true;
3845
+ sawLong = true;
3846
+ const covered = [];
3847
+ for (let i = text2.indexOf(long); i >= 0; i = text2.indexOf(long, i + 1)) covered.push([i, i + long.length]);
3848
+ for (let i = text2.indexOf(short); i >= 0; i = text2.indexOf(short, i + 1)) {
3849
+ if (!covered.some(([from, to]) => i >= from && i + short.length <= to)) return false;
3850
+ }
3851
+ return true;
3852
+ })
3853
+ );
3854
+ return ok && sawLong;
3855
+ }
3856
+ var JSON_ESCAPES = { n: "\n", r: "\r", t: " ", b: "\b", f: "\f", '"': '"', "\\": "\\", "/": "/" };
3857
+ function percentDecoded(text2) {
3858
+ return text2.replace(/(?:%[0-9a-f]{2})+/gi, (run) => {
3859
+ try {
3860
+ return decodeURIComponent(run);
3861
+ } catch {
3862
+ return run;
3817
3863
  }
3818
- return true;
3819
3864
  });
3820
3865
  }
3866
+ function base64InPlace(text2) {
3867
+ return text2.replace(/[A-Za-z0-9+/_-]{12,}={0,2}/g, (token) => {
3868
+ const decoded = Buffer.from(token, "base64").toString("utf8");
3869
+ return decoded.includes("\uFFFD") ? token : decoded;
3870
+ });
3871
+ }
3872
+ function readingForms(text2) {
3873
+ const forms = /* @__PURE__ */ new Set([text2]);
3874
+ let layer = text2;
3875
+ for (let i = 0; i < 4; i++) {
3876
+ const next = percentDecoded(layer);
3877
+ if (next === layer) break;
3878
+ forms.add(layer = next);
3879
+ }
3880
+ for (const form of [...forms]) {
3881
+ forms.add(form.replace(/\\(?:u([0-9a-f]{4})|(.))/gi, (m, hex, ch) => hex ? String.fromCharCode(parseInt(hex, 16)) : JSON_ESCAPES[ch] ?? m));
3882
+ }
3883
+ for (const form of [...forms]) forms.add(base64InPlace(form));
3884
+ return [...forms];
3885
+ }
3821
3886
  function mergeEdgeReadings(found, bodies) {
3822
3887
  const best = (f) => Math.min(...f.where.values());
3823
3888
  const valueOf2 = (key, kind) => key.slice(kind.length + 1);
@@ -3911,15 +3976,15 @@ function parseEventMap(text2, file) {
3911
3976
  const map = { events: /* @__PURE__ */ Object.create(null), paths: /* @__PURE__ */ Object.create(null) };
3912
3977
  const events = json.events ?? {};
3913
3978
  if (!isRecord(events)) throw new Error(`${file}: "events" must be an object.`);
3914
- for (const [from, to] of Object.entries(events)) {
3915
- if (!EVENT_NAME.test(from)) throw new Error(`${file}: "events" has a name that is not an event name.`);
3979
+ for (const [position, [from, to]] of Object.entries(events).map((e, i) => [i + 1, e])) {
3980
+ if (!EVENT_NAME.test(from)) throw new Error(`${file}: "events" key ${position} is not an event name.`);
3916
3981
  if (typeof to !== "string" || !EVENT_NAME.test(to)) throw new Error(`${file}: events.${from} must be an event name.`);
3917
3982
  map.events[from] = to;
3918
3983
  }
3919
3984
  const paths = json.paths ?? {};
3920
3985
  if (!isRecord(paths)) throw new Error(`${file}: "paths" must be an object.`);
3921
- for (const [event, renames] of Object.entries(paths)) {
3922
- if (!EVENT_NAME.test(event)) throw new Error(`${file}: "paths" has a name that is not an event name.`);
3986
+ for (const [position, [event, renames]] of Object.entries(paths).map((e, i) => [i + 1, e])) {
3987
+ if (!EVENT_NAME.test(event)) throw new Error(`${file}: "paths" key ${position} is not an event name.`);
3923
3988
  if (!isRecord(renames)) throw new Error(`${file}: paths.${event} must be an object.`);
3924
3989
  const out = /* @__PURE__ */ Object.create(null);
3925
3990
  if (Object.hasOwn(renames, ROOT) && Object.keys(renames).length > 1) throw new Error(`${file}: paths.${event} with the "${ROOT}" source key takes no other key.`);
@@ -3947,15 +4012,16 @@ function renamePath(path, renames) {
3947
4012
  }
3948
4013
  return path;
3949
4014
  }
3950
- function mapPushGroups(groups, rename2, paths = {}) {
4015
+ function mapPushGroups(groups, rename2, paths = {}, pathKeys = (recorded, final) => [final, recorded]) {
3951
4016
  return groups.map((g) => {
3952
4017
  const event = rename2(g.event);
3953
- const renames = Object.hasOwn(paths, event) ? paths[event] : void 0;
4018
+ const key = pathKeys(g.event, event).find((k) => Object.hasOwn(paths, k));
4019
+ const renames = key === void 0 ? void 0 : paths[key];
3954
4020
  if (!renames) return { ...g, event };
3955
4021
  const under = Object.hasOwn(renames, ROOT) ? renames[ROOT] : void 0;
3956
4022
  if (under !== void 0) {
3957
4023
  const moved = g.paths.map((p) => ({ ...p, path: p.path.startsWith("[") ? `${under}${p.path}` : `${under}.${p.path}` }));
3958
- return { ...g, event, paths: g.paths.some((p) => p.path === "event") ? g.paths : [{ path: "event", types: ["string"] }, ...moved] };
4024
+ return { ...g, event, ...g.kind === void 0 ? {} : { kind: "object" }, paths: g.paths.some((p) => p.path === "event") ? g.paths : [{ path: "event", types: ["string"] }, ...moved] };
3959
4025
  }
3960
4026
  const toGtag = Object.values(renames).includes(ROOT);
3961
4027
  const mapped = [];
@@ -3964,17 +4030,18 @@ function mapPushGroups(groups, rename2, paths = {}) {
3964
4030
  const path = renamePath(p.path, renames);
3965
4031
  if (path !== void 0) mapped.push({ ...p, path });
3966
4032
  }
3967
- return { ...g, event, paths: mapped };
4033
+ return { ...g, event, ...toGtag && g.kind !== void 0 ? { kind: "gtag" } : {}, paths: mapped };
3968
4034
  });
3969
4035
  }
3970
4036
  function normalizePushGroups(groups, userMap) {
3971
- const rename2 = (event) => {
3972
- const user = userMap?.events;
4037
+ const user = userMap?.events;
4038
+ const userName = (event) => {
3973
4039
  const named = builtInEventName(event);
3974
- const mapped = user !== void 0 && Object.hasOwn(user, event) ? user[event] : user !== void 0 && Object.hasOwn(user, named) ? user[named] : named;
3975
- return builtInEventName(mapped);
4040
+ return user !== void 0 && Object.hasOwn(user, event) ? user[event] : user !== void 0 && Object.hasOwn(user, named) ? user[named] : named;
3976
4041
  };
3977
- return mapPushGroups(groups, rename2, userMap?.paths);
4042
+ const rename2 = (event) => builtInEventName(userName(event));
4043
+ const pathKeys = (recorded, final) => [final, recorded, userName(recorded)];
4044
+ return mapPushGroups(groups, rename2, userMap?.paths, pathKeys);
3978
4045
  }
3979
4046
 
3980
4047
  // packages/expect/src/push-shape.ts
@@ -3983,6 +4050,9 @@ var NO_STEP = "(no step)";
3983
4050
  var EVENT_CHARS = /^[A-Za-z0-9_.:-]+$/;
3984
4051
  var MAX_DEPTH2 = 8;
3985
4052
  var MAX_PATHS = 200;
4053
+ var GTAG_COMMANDS = /* @__PURE__ */ new Set(["config", "consent", "event", "get", "js", "set"]);
4054
+ var GTAG_OTHER = "gtag (other)";
4055
+ var MAX_ARGUMENTS = 16;
3986
4056
  function safeName(name) {
3987
4057
  return EVENT_CHARS.test(name) && !isValueSegment(name) && guardFieldName(name) === name ? name : OTHER_NAME;
3988
4058
  }
@@ -4007,23 +4077,44 @@ function walk(value, path, depth, out) {
4007
4077
  function isGtagCommand(args) {
4008
4078
  return typeof args[0] === "string";
4009
4079
  }
4010
- function eventLabel(e) {
4080
+ function argumentsLike(args) {
4081
+ const [item] = args;
4082
+ if (args.length !== 1 || typeof item !== "object" || item === null || Array.isArray(item)) return void 0;
4083
+ const keys = Object.keys(item);
4084
+ if (keys.length < 1 || keys.length > MAX_ARGUMENTS || !keys.every((k, i) => Object.hasOwn(item, String(i)) && k === String(i))) return void 0;
4085
+ const list3 = keys.map((_, i) => item[String(i)]);
4086
+ return typeof list3[0] === "string" ? list3 : void 0;
4087
+ }
4088
+ function commandOf(e) {
4089
+ if (isGtagCommand(e.args)) return { list: e.args, fromObject: false };
4090
+ const list3 = argumentsLike(e.args);
4091
+ return list3 !== void 0 && isGtagCommand(list3) ? { list: list3, fromObject: true } : void 0;
4092
+ }
4093
+ function commandLabel(command) {
4094
+ const [name, second] = command.list;
4095
+ if (command.fromObject && typeof second === "string") {
4096
+ if (name === "consent") return `consent ${safeName(second)}`;
4097
+ if (name === "event") return safeName(second);
4098
+ }
4099
+ return GTAG_COMMANDS.has(name) ? `gtag ${name}` : GTAG_OTHER;
4100
+ }
4101
+ function eventLabel(e, command) {
4011
4102
  if (e.isConsentCommand) return `consent ${String(e.args[1])}`;
4012
4103
  if (e.event !== null) return safeName(e.event);
4013
- return isGtagCommand(e.args) ? `gtag ${safeName(e.args[0])}` : NO_EVENT;
4104
+ return command === void 0 ? NO_EVENT : commandLabel(command);
4014
4105
  }
4015
4106
  function frameKind(e) {
4016
4107
  return e.frame === void 0 ? "unknown" : e.frame.main ? "main" : "embedded";
4017
4108
  }
4018
- function collectPaths(e, into) {
4109
+ function collectPaths(e, command, into) {
4019
4110
  if (e.event?.startsWith("gtm.")) return;
4020
- if (e.isConsentCommand) {
4021
- const signals = e.args[2];
4111
+ if (e.isConsentCommand || command?.fromObject && command.list[0] === "consent") {
4112
+ const signals = (command?.fromObject ? command.list : e.args)[2];
4022
4113
  if (typeof signals === "object" && signals !== null) for (const [name, value] of Object.entries(signals)) walk(value, safeKey(name), 0, into);
4023
4114
  return;
4024
4115
  }
4025
- if (isGtagCommand(e.args)) {
4026
- for (const arg of e.args.slice(e.args[0] === "set" ? 1 : 2)) walk(arg, "", 0, into);
4116
+ if (command !== void 0) {
4117
+ for (const arg of command.list.slice(command.list[0] === "set" ? 1 : 2)) walk(arg, "", 0, into);
4027
4118
  return;
4028
4119
  }
4029
4120
  for (const arg of e.args) walk(arg, "", 0, into);
@@ -4033,14 +4124,16 @@ function pushShapes(records) {
4033
4124
  const steps = /* @__PURE__ */ new Map();
4034
4125
  for (const e of records.dataLayerEvents) {
4035
4126
  const step = e.stepId === null ? NO_STEP : labels.get(e.stepId) ?? NO_STEP;
4036
- const event = eventLabel(e);
4127
+ const command = commandOf(e);
4128
+ const event = eventLabel(e, command);
4129
+ const kind = command === void 0 ? "object" : "gtag";
4037
4130
  const frame = frameKind(e);
4038
4131
  const groups = steps.get(step) ?? steps.set(step, /* @__PURE__ */ new Map()).get(step);
4039
- const key = JSON.stringify([event, frame]);
4040
- const group = groups.get(key) ?? groups.set(key, { shape: { event, frame, count: 0, paths: [], ids: [] }, types: /* @__PURE__ */ new Map() }).get(key);
4132
+ const key = JSON.stringify([event, kind, frame]);
4133
+ const group = groups.get(key) ?? groups.set(key, { shape: { event, kind, frame, count: 0, paths: [], ids: [] }, types: /* @__PURE__ */ new Map() }).get(key);
4041
4134
  group.shape.count += 1;
4042
4135
  group.shape.ids.push(e.id);
4043
- collectPaths(e, group.types);
4136
+ collectPaths(e, command, group.types);
4044
4137
  }
4045
4138
  return {
4046
4139
  pushes: records.dataLayerEvents.length,
@@ -4096,6 +4189,7 @@ function diffRuns(a, b, options = {}) {
4096
4189
  const pushesB = pushGroups(b);
4097
4190
  if (pushesA.length > 0 || pushesB.length > 0) {
4098
4191
  result.dataLayer = diffPushes(pushesA, pushesB, { acrossFrames: options.acrossFrames, epochOrder: epochOrder(b), eventMap: options.eventMap });
4192
+ result.warnings.push(...result.dataLayer.kindChanged.map((k) => `push kind changed: ${k.event}`));
4099
4193
  }
4100
4194
  return result;
4101
4195
  }
@@ -4113,8 +4207,8 @@ function pushGroups(run) {
4113
4207
  for (const [epoch, dataLayerEvents] of [...byEpoch].sort(([x], [y]) => x < y ? -1 : x > y ? 1 : 0)) {
4114
4208
  for (const step of pushShapes({ steps: run.steps, dataLayerEvents }).steps) {
4115
4209
  for (const shape of step.events) {
4116
- const id = JSON.stringify([epoch, shape.event, shape.frame]);
4117
- const entry = groups.get(id) ?? groups.set(id, { group: { epoch, event: shape.event, frame: shape.frame, paths: [] }, types: /* @__PURE__ */ new Map() }).get(id);
4210
+ const id = JSON.stringify([epoch, shape.event, shape.kind, shape.frame]);
4211
+ const entry = groups.get(id) ?? groups.set(id, { group: { epoch, event: shape.event, kind: shape.kind, frame: shape.frame, paths: [] }, types: /* @__PURE__ */ new Map() }).get(id);
4118
4212
  for (const p of shape.paths) {
4119
4213
  const set = entry.types.get(p.path) ?? entry.types.set(p.path, /* @__PURE__ */ new Set()).get(p.path);
4120
4214
  for (const t of p.types) set.add(t);
@@ -4127,49 +4221,61 @@ function pushGroups(run) {
4127
4221
  paths: [...types].sort(([x], [y]) => x < y ? -1 : x > y ? 1 : 0).map(([path, set]) => ({ path, types: [...set].sort() }))
4128
4222
  }));
4129
4223
  }
4130
- function pushNodes(groups, acrossFrames) {
4224
+ function pushNodes(groups, acrossFrames, mergeKinds) {
4131
4225
  const nodes = /* @__PURE__ */ new Map();
4132
4226
  for (const g of groups) {
4133
4227
  const frame = acrossFrames ? "any" : g.frame;
4134
- const id = JSON.stringify([g.epoch, g.event, frame]);
4135
- const node = nodes.get(id) ?? { epoch: g.epoch, event: g.event, frame, frames: [], types: /* @__PURE__ */ new Map() };
4228
+ const kind = mergeKinds ? void 0 : g.kind;
4229
+ const id = JSON.stringify([g.epoch, g.event, kind ?? null, frame]);
4230
+ const node = nodes.get(id) ?? { epoch: g.epoch, event: g.event, ...kind === void 0 ? {} : { kind }, frame, frames: [], types: /* @__PURE__ */ new Map() };
4136
4231
  if (!node.frames.includes(g.frame)) node.frames.push(g.frame);
4137
4232
  for (const p of g.paths) node.types.set(p.path, [.../* @__PURE__ */ new Set([...node.types.get(p.path) ?? [], ...p.types])].sort());
4138
4233
  nodes.set(id, node);
4139
4234
  }
4140
4235
  return nodes;
4141
4236
  }
4142
- var nodeRef = (n) => ({ epoch: n.epoch, event: n.event, frame: n.frame });
4237
+ var nodeRef = (n) => ({ epoch: n.epoch, event: n.event, ...n.kind === void 0 ? {} : { kind: n.kind }, frame: n.frame });
4143
4238
  var typesId = (n) => JSON.stringify([...n.types].sort(([x], [y]) => x < y ? -1 : x > y ? 1 : 0));
4144
4239
  function diffPushes(a, b, options = {}) {
4145
- const result = { eventsAdded: [], eventsRemoved: [], pathsAdded: [], pathsRemoved: [], typeChanges: [], moved: [], changed: false };
4146
- const na = pushNodes(normalizePushGroups(a, options.eventMap), options.acrossFrames ?? false);
4147
- const nb = pushNodes(normalizePushGroups(b), options.acrossFrames ?? false);
4240
+ const result = { eventsAdded: [], eventsRemoved: [], pathsAdded: [], pathsRemoved: [], typeChanges: [], moved: [], kindChanged: [], changed: false };
4241
+ const mergeKinds = [...a, ...b].some((g) => g.kind === void 0);
4242
+ const na = pushNodes(normalizePushGroups(a, options.eventMap), options.acrossFrames ?? false, mergeKinds);
4243
+ const nb = pushNodes(normalizePushGroups(b), options.acrossFrames ?? false, mergeKinds);
4148
4244
  const gone = [];
4149
4245
  const fresh = [];
4246
+ const compare = (x, y) => {
4247
+ for (const [path, types] of y.types) {
4248
+ const before = x.types.get(path);
4249
+ if (!before) result.pathsAdded.push({ ...nodeRef(y), path, types });
4250
+ else if (before.join() !== types.join()) result.typeChanges.push({ ...nodeRef(y), path, a: before, b: types });
4251
+ }
4252
+ for (const [path, types] of x.types) if (!y.types.has(path)) result.pathsRemoved.push({ ...nodeRef(x), path, types });
4253
+ if (x.frames.slice().sort().join() !== y.frames.slice().sort().join()) {
4254
+ result.moved.push({ event: y.event, kind: "frame", epoch: y.epoch, from: x.frames.slice().sort().join("+"), to: y.frames.slice().sort().join("+") });
4255
+ }
4256
+ };
4150
4257
  for (const id of [.../* @__PURE__ */ new Set([...na.keys(), ...nb.keys()])].sort()) {
4151
4258
  const x = na.get(id);
4152
4259
  const y = nb.get(id);
4153
4260
  if (!x) fresh.push(y);
4154
4261
  else if (!y) gone.push(x);
4155
- else {
4156
- for (const [path, types] of y.types) {
4157
- const before = x.types.get(path);
4158
- if (!before) result.pathsAdded.push({ ...nodeRef(y), path, types });
4159
- else if (before.join() !== types.join()) result.typeChanges.push({ ...nodeRef(y), path, a: before, b: types });
4160
- }
4161
- for (const [path, types] of x.types) if (!y.types.has(path)) result.pathsRemoved.push({ ...nodeRef(x), path, types });
4162
- if (x.frames.slice().sort().join() !== y.frames.slice().sort().join()) {
4163
- result.moved.push({ event: y.event, kind: "frame", epoch: y.epoch, from: x.frames.slice().sort().join("+"), to: y.frames.slice().sort().join("+") });
4164
- }
4165
- }
4262
+ else compare(x, y);
4263
+ }
4264
+ const sole = (nodes, n) => [...nodes.values()].filter((o) => o.epoch === n.epoch && o.event === n.event && o.frame === n.frame).length === 1;
4265
+ for (const g of [...gone]) {
4266
+ const f = fresh.find((o) => o.epoch === g.epoch && o.event === g.event && o.frame === g.frame && g.kind !== void 0 && o.kind !== void 0 && sole(na, g) && sole(nb, o));
4267
+ if (!f) continue;
4268
+ gone.splice(gone.indexOf(g), 1);
4269
+ fresh.splice(fresh.indexOf(f), 1);
4270
+ result.kindChanged.push({ epoch: g.epoch, event: g.event, frame: g.frame, from: g.kind, to: f.kind });
4271
+ compare(g, f);
4166
4272
  }
4167
4273
  const order = options.epochOrder ?? [];
4168
4274
  const taken = /* @__PURE__ */ new Set();
4169
4275
  for (const g of gone) {
4170
4276
  const i = order.indexOf(g.epoch);
4171
4277
  const match = fresh.find((f) => {
4172
- if (taken.has(f) || f.event !== g.event || f.frame !== g.frame || typesId(f) !== typesId(g)) return false;
4278
+ if (taken.has(f) || f.event !== g.event || f.kind !== g.kind || f.frame !== g.frame || typesId(f) !== typesId(g)) return false;
4173
4279
  const j = order.indexOf(f.epoch);
4174
4280
  return i >= 0 && j >= 0 && Math.abs(i - j) === 1 && order.filter((l) => l === g.epoch || l === f.epoch).length === 2;
4175
4281
  });
@@ -4422,6 +4528,7 @@ var ProjectConfigError = class extends Error {
4422
4528
  var CONFIG_KEYS = ["configSchemaVersion", "site", "out", "options"];
4423
4529
  var CONFIG_OPTION_KEYS = ["allowUnknownDestination", "builtins", "firstPartyHosts", "platformHosts", "serverHosts", "unloadGapIgnore", "dataLayerNames", "identifierFields"];
4424
4530
  var REFUSED_KEYS = ["network", "serverContainer", "serverContainerConfig", "allowTestPayment", "gtmOverride"];
4531
+ var CONTROL_BYTE = /[\u0000-\u001f\u007f]/;
4425
4532
  function isMap2(v) {
4426
4533
  return typeof v === "object" && v !== null && !Array.isArray(v);
4427
4534
  }
@@ -4466,6 +4573,10 @@ function parseProjectConfig(text2, file) {
4466
4573
  visit(doc, {
4467
4574
  Pair(_, pair) {
4468
4575
  const key = pair.key;
4576
+ if (isScalar(key) && typeof key.value === "string" && key.type === Scalar.PLAIN && CONTROL_BYTE.test(key.value)) {
4577
+ report(lineAt(key), "", "a key holds a control character");
4578
+ return visit.BREAK;
4579
+ }
4469
4580
  if (!isScalar(key) || typeof key.value !== "string" || key.type !== Scalar.PLAIN || key.value === "<<") return refuse(isScalar(key) || isAlias(key) ? key : key);
4470
4581
  },
4471
4582
  Node(_, node) {
@@ -4635,13 +4746,24 @@ async function routeCollector(context, handler, now) {
4635
4746
  // packages/recorder/src/datalayer.ts
4636
4747
  var DATALAYER_BINDING = "__tagreeveDataLayer";
4637
4748
  var DEFAULT_DATALAYER = "dataLayer";
4749
+ var DATALAYER_TALLY = "__tagreeveTally";
4750
+ function hookedLayerNames(names = []) {
4751
+ return [.../* @__PURE__ */ new Set([DEFAULT_DATALAYER, ...names.filter((name) => name !== DEFAULT_DATALAYER && isDataLayerName(name))])];
4752
+ }
4638
4753
  function dataLayerInitScript(names = []) {
4639
- const all = [DEFAULT_DATALAYER, ...names.filter((name) => name !== DEFAULT_DATALAYER && isDataLayerName(name))];
4640
4754
  return `(() => {
4641
4755
  const binding = ${JSON.stringify(DATALAYER_BINDING)};
4642
- const names = ${JSON.stringify([...new Set(all)])};
4756
+ const names = ${JSON.stringify(hookedLayerNames(names))};
4643
4757
  const unsafe = ${JSON.stringify(NEVER_TRAPPED_NAMES)};
4644
4758
  const MAX = 10000;
4759
+ const token = (() => {
4760
+ try {
4761
+ return Array.from(crypto.getRandomValues(new Uint8Array(12)), (b) => b.toString(16).padStart(2, '0')).join('');
4762
+ } catch {
4763
+ return Math.random().toString(16).slice(2) + Math.random().toString(16).slice(2);
4764
+ }
4765
+ })();
4766
+ const seq = {};
4645
4767
  const clock = () => performance.timeOrigin + performance.now();
4646
4768
  const plain = (k, v) => (typeof v === 'function' || v instanceof Node ? undefined : v);
4647
4769
  // Keeps the top levels, so the event name and ids survive a large push. Deeper values become a marker.
@@ -4667,24 +4789,173 @@ function dataLayerInitScript(names = []) {
4667
4789
  return JSON.stringify(['[unserializable]']);
4668
4790
  }
4669
4791
  };
4670
- const report = (item, layerName) => {
4671
- const isArgs = Object.prototype.toString.call(item) === '[object Arguments]';
4672
- const send = window[binding];
4673
- if (typeof send !== 'function') return;
4674
- const payload = { t: clock(), args: safe(isArgs ? Array.from(item) : [item]) };
4675
- if (layerName !== 'dataLayer') payload.layer = layerName;
4676
- send(payload).catch(() => {});
4792
+ const post = (payload) => {
4793
+ try {
4794
+ const send = window[binding];
4795
+ if (typeof send !== 'function') return false;
4796
+ Promise.resolve(send(payload)).catch(() => {});
4797
+ return true;
4798
+ } catch {
4799
+ return false;
4800
+ }
4801
+ };
4802
+ const argsOf = (item) => safe(Object.prototype.toString.call(item) === '[object Arguments]' ? Array.from(item) : [item]);
4803
+ const stampOf = (item) => {
4804
+ try {
4805
+ const id = item !== null && typeof item === 'object' ? item['gtm.uniqueEventId'] : undefined;
4806
+ return typeof id === 'number' ? id : undefined;
4807
+ } catch {
4808
+ return undefined;
4809
+ }
4810
+ };
4811
+ const defer = queueMicrotask;
4812
+ const callIt = Reflect.apply;
4813
+ // Nothing here may throw into page code, so every entry point swallows its errors.
4814
+ const guarded = (fn) => (...a) => {
4815
+ try {
4816
+ return fn(...a);
4817
+ } catch {
4818
+ return undefined;
4819
+ }
4677
4820
  };
4821
+ const hooks = new WeakMap();
4822
+ let reading = false;
4823
+ // Page code always sees the function it assigned to push last. Only items appended at the end are recorded:
4824
+ // through the base push, which wrappers save and call through, or by length growth for pushes that skip it.
4678
4825
  const hook = (layer, layerName) => {
4679
- if (!Array.isArray(layer) || layer.__tagreeveHooked) return;
4680
- Object.defineProperty(layer, '__tagreeveHooked', { value: true });
4681
- const push = layer.push;
4682
- layer.push = function (...items) {
4683
- for (const item of items) report(item, layerName);
4684
- return push.apply(this, items);
4826
+ if (!Array.isArray(layer)) return;
4827
+ const existing = hooks.get(layer);
4828
+ if (existing) return existing;
4829
+ // Another frame's hook owns this array; a second one would replace the page's push and record twice.
4830
+ if (Object.prototype.hasOwnProperty.call(layer, '__tagreeveHooked')) return;
4831
+ try {
4832
+ Object.defineProperty(layer, '__tagreeveHooked', { value: true });
4833
+ } catch {}
4834
+ const info = { a: (seq[layerName] = (seq[layerName] || 0) + 1), posted: 0 };
4835
+ let known = 0;
4836
+ let prefix = [];
4837
+ let queued = false;
4838
+ const intact = (length) => {
4839
+ try {
4840
+ if (length < known) return false;
4841
+ for (let i = 0; i < known; i++) if (!Object.is(layer[i], prefix[i])) return false;
4842
+ return true;
4843
+ } catch {
4844
+ return false;
4845
+ }
4846
+ };
4847
+ const resync = (length) => {
4848
+ known = length;
4849
+ prefix = new Array(length);
4850
+ try {
4851
+ for (let i = 0; i < length; i++) prefix[i] = layer[i];
4852
+ } catch {}
4853
+ };
4854
+ // A changed slot before the known length means an in-place edit (unshift, splice, sort, shrink): record nothing.
4855
+ const fresh = (trusted) => {
4856
+ const length = layer.length;
4857
+ if (!trusted && !intact(length)) {
4858
+ resync(length);
4859
+ return [];
4860
+ }
4861
+ const added = [];
4862
+ for (let i = known; i < length; i++) {
4863
+ try {
4864
+ const present = i in layer;
4865
+ const item = layer[i];
4866
+ prefix[i] = item;
4867
+ if (present) added.push(item);
4868
+ } catch {
4869
+ prefix[i] = undefined;
4870
+ }
4871
+ }
4872
+ known = length;
4873
+ return added;
4874
+ };
4875
+ // The id is read in a microtask, so an id a wrapper sets after the push returned is picked up.
4876
+ const report = (added, t) => {
4877
+ const items = [];
4878
+ for (const item of added) {
4879
+ try {
4880
+ items.push({ item, args: argsOf(item) });
4881
+ } catch {}
4882
+ }
4883
+ if (items.length === 0) return;
4884
+ info.posted += items.length;
4885
+ const at = t === undefined ? clock() : t;
4886
+ defer(guarded(() => {
4887
+ for (const { item, args } of items) {
4888
+ const payload = { t: at, args, uid: stampOf(item), d: token, a: info.a };
4889
+ if (layerName !== 'dataLayer') payload.layer = layerName;
4890
+ if (!post(payload)) info.posted -= 1;
4891
+ }
4892
+ }));
4893
+ };
4894
+ const sync = guarded(() => {
4895
+ queued = false;
4896
+ report(fresh(false));
4897
+ });
4898
+ const schedule = guarded(() => {
4899
+ if (queued) return;
4900
+ queued = true;
4901
+ defer(sync);
4902
+ });
4903
+ const base = Object.prototype.hasOwnProperty.call(layer, 'push') ? Array.prototype.push : layer.push;
4904
+ const own = Object.getOwnPropertyDescriptor(layer, 'push');
4905
+ const record = function (...items) {
4906
+ let t;
4907
+ let synced = false;
4908
+ try {
4909
+ if (this === layer) {
4910
+ if (layer.length !== known) sync();
4911
+ synced = layer.length === known;
4912
+ t = clock();
4913
+ }
4914
+ } catch {}
4915
+ try {
4916
+ return callIt(base, this, items);
4917
+ } finally {
4918
+ try {
4919
+ if (this === layer) report(fresh(synced), t);
4920
+ } catch {}
4921
+ }
4685
4922
  };
4686
- for (const item of layer) report(item, layerName);
4923
+ let assigned = own && 'value' in own ? own.value : record;
4924
+ const state = { info, sync, schedule };
4925
+ hooks.set(layer, state);
4926
+ // A push accessor the page defined stays in place; the growth check still records.
4927
+ const foreign = own && !('value' in own);
4928
+ try {
4929
+ if (!foreign) Object.defineProperty(layer, 'push', {
4930
+ configurable: true,
4931
+ enumerable: false,
4932
+ get: guarded(() => {
4933
+ schedule();
4934
+ return assigned;
4935
+ }),
4936
+ set: guarded((fn) => {
4937
+ assigned = fn;
4938
+ schedule();
4939
+ }),
4940
+ });
4941
+ } catch {}
4942
+ try {
4943
+ report(fresh(false));
4944
+ } catch {}
4945
+ return state;
4687
4946
  };
4947
+ const current = {};
4948
+ const syncAll = guarded(() => {
4949
+ for (const name of names) {
4950
+ const state = hooks.get(current[name]);
4951
+ if (state) state.sync();
4952
+ }
4953
+ });
4954
+ for (const event of ['DOMContentLoaded', 'load', 'pagehide']) {
4955
+ try {
4956
+ addEventListener(event, syncAll);
4957
+ } catch {}
4958
+ }
4688
4959
  const trappable = (name) => {
4689
4960
  if (unsafe.includes(name)) return false;
4690
4961
  const found = Object.getOwnPropertyDescriptor(window, name);
@@ -4693,18 +4964,55 @@ function dataLayerInitScript(names = []) {
4693
4964
  };
4694
4965
  for (const name of names) {
4695
4966
  if (!trappable(name)) continue;
4696
- let current = window[name];
4697
- hook(current, name);
4967
+ current[name] = window[name];
4968
+ try {
4969
+ hook(current[name], name);
4970
+ } catch {}
4698
4971
  Object.defineProperty(window, name, {
4699
4972
  configurable: true,
4700
4973
  enumerable: true,
4701
- get: () => current,
4974
+ get: () => {
4975
+ try {
4976
+ if (!reading) {
4977
+ const state = hooks.get(current[name]);
4978
+ if (state) state.schedule();
4979
+ }
4980
+ } catch {}
4981
+ return current[name];
4982
+ },
4702
4983
  set: (value) => {
4703
- current = value;
4704
- hook(value, name);
4984
+ const previous = current[name];
4985
+ current[name] = value;
4986
+ try {
4987
+ const old = hooks.get(previous);
4988
+ if (old) old.sync();
4989
+ if (old && name === 'dataLayer' && Array.isArray(value) && value !== previous) post({ t: clock(), args: '[]', reassigned: true });
4990
+ hook(value, name);
4991
+ } catch {}
4705
4992
  },
4706
4993
  });
4707
4994
  }
4995
+ Object.defineProperty(window, ${JSON.stringify(DATALAYER_TALLY)}, {
4996
+ value: () => {
4997
+ const arrays = [];
4998
+ for (const name of names) {
4999
+ try {
5000
+ let layer;
5001
+ reading = true;
5002
+ try {
5003
+ layer = window[name];
5004
+ } finally {
5005
+ reading = false;
5006
+ }
5007
+ if (!Array.isArray(layer)) continue;
5008
+ const state = hooks.get(layer);
5009
+ if (state) state.sync();
5010
+ arrays.push({ layer: name, a: state ? state.info.a : null, length: layer.length, posted: state ? state.info.posted : 0 });
5011
+ } catch {}
5012
+ }
5013
+ return { d: token, arrays };
5014
+ },
5015
+ });
4708
5016
  })();`;
4709
5017
  }
4710
5018
  function isDataLayerName(name) {
@@ -4735,7 +5043,7 @@ function dataLayerEventFromPayload(payload, runId, offset, frame) {
4735
5043
  } catch {
4736
5044
  return void 0;
4737
5045
  }
4738
- if (!Array.isArray(args) || typeof payload.t !== "number") return void 0;
5046
+ if (!Array.isArray(args) || typeof payload.t !== "number" || payload.reassigned) return void 0;
4739
5047
  const t = pageTimeToEpoch(payload.t, offset);
4740
5048
  return {
4741
5049
  type: "dataLayerEvent",
@@ -4744,7 +5052,7 @@ function dataLayerEventFromPayload(payload, runId, offset, frame) {
4744
5052
  stepId: null,
4745
5053
  t,
4746
5054
  event: eventName(args),
4747
- gtmUniqueEventId: uniqueEventId(args),
5055
+ gtmUniqueEventId: typeof payload.uid === "number" ? payload.uid : uniqueEventId(args),
4748
5056
  args,
4749
5057
  isConsentCommand: isConsentCommand(args),
4750
5058
  frame: { main: frame.main, n: frame.n },
@@ -4880,7 +5188,7 @@ function buildUnloadGapFlags({ runId, networkMode, events, hits, navigations, ru
4880
5188
  runId,
4881
5189
  "unloadGap",
4882
5190
  [event.id],
4883
- `A frame pushed "${name}" ${seconds} s before ${unload} and no ga4 hit for it was recorded after it. The frame may have sent the hit while unloading, ${unloadGapAdvice(networkMode)} (design \xA75.3).`
5191
+ `A frame pushed "${guardFieldName(name) === name && !isValueSegment(name) ? name : OTHER_NAME}" ${seconds} s before ${unload} and no ga4 hit for it was recorded after it. The frame may have sent the hit while unloading, ${unloadGapAdvice(networkMode)} (design \xA75.3).`
4884
5192
  )
4885
5193
  );
4886
5194
  }
@@ -5532,6 +5840,82 @@ import {
5532
5840
  request as playwrightRequest
5533
5841
  } from "playwright";
5534
5842
 
5843
+ // packages/recorder/src/datalayer-tally.ts
5844
+ var MAX_TALLY_KEYS = 256;
5845
+ var PayloadCounts = class _PayloadCounts {
5846
+ counts = /* @__PURE__ */ new Map();
5847
+ cappedDocuments = /* @__PURE__ */ new Set();
5848
+ static key(frame, d, layer, a) {
5849
+ return `${frame}\0${d}\0${layer}\0${a ?? ""}`;
5850
+ }
5851
+ static documentKey(frame, d) {
5852
+ return `${frame}\0${d}`;
5853
+ }
5854
+ add(payload, frame, names) {
5855
+ const { d, a } = payload;
5856
+ const layer = payload.layer === void 0 ? "dataLayer" : payload.layer;
5857
+ if (typeof d !== "string" || d.length > 64 || !Number.isSafeInteger(a) || a < 0) return;
5858
+ if (typeof layer !== "string" || !names.includes(layer)) return;
5859
+ const key = _PayloadCounts.key(frame, d, layer, a);
5860
+ const seen = this.counts.get(key);
5861
+ if (seen !== void 0) this.counts.set(key, seen + 1);
5862
+ else if (this.counts.size < MAX_TALLY_KEYS) this.counts.set(key, 1);
5863
+ else this.cappedDocuments.add(_PayloadCounts.documentKey(frame, d));
5864
+ }
5865
+ /** `undefined` for a document that had a key refused at the cap. */
5866
+ received(frame, d, layer, a) {
5867
+ const seen = this.counts.get(_PayloadCounts.key(frame, d, layer, a));
5868
+ if (seen !== void 0) return seen;
5869
+ return this.cappedDocuments.has(_PayloadCounts.documentKey(frame, d)) ? void 0 : 0;
5870
+ }
5871
+ };
5872
+ var isCount = (value) => Number.isSafeInteger(value) && value >= 0;
5873
+ function validateTally(frame, value, names) {
5874
+ if (typeof value !== "object" || value === null) return null;
5875
+ const { d, arrays } = value;
5876
+ if (typeof d !== "string" || d.length > 64 || !Array.isArray(arrays)) return null;
5877
+ const kept = [];
5878
+ for (const entry of arrays) {
5879
+ if (typeof entry !== "object" || entry === null) continue;
5880
+ const { layer, a, length, posted } = entry;
5881
+ if (typeof layer !== "string" || !names.includes(layer)) continue;
5882
+ if (!isCount(length) || !isCount(posted) || !(a === null || isCount(a))) continue;
5883
+ kept.push({ layer, a, length, posted });
5884
+ }
5885
+ return { frame, d, arrays: kept };
5886
+ }
5887
+ function postedAhead(tallies, counts) {
5888
+ return tallies.some(
5889
+ (tally) => tally.arrays.some((array) => {
5890
+ if (array.a === null) return false;
5891
+ const received = counts.received(tally.frame, tally.d, array.layer, array.a);
5892
+ return received !== void 0 && received < array.posted;
5893
+ })
5894
+ );
5895
+ }
5896
+ function buildTallyFlags(runId, tallies, counts) {
5897
+ const flags2 = [];
5898
+ const done = /* @__PURE__ */ new Set();
5899
+ for (const tally of tallies) {
5900
+ for (const array of tally.arrays) {
5901
+ const received = counts.received(tally.frame, tally.d, array.layer, array.a);
5902
+ if (received === void 0 || array.length <= received) continue;
5903
+ const once = `${tally.frame}\0${array.layer}`;
5904
+ if (done.has(once)) continue;
5905
+ done.add(once);
5906
+ flags2.push({
5907
+ type: "flag",
5908
+ id: newId("flag"),
5909
+ runId,
5910
+ kind: "dataLayerIncomplete",
5911
+ recordIds: [],
5912
+ detail: `Frame ${tally.frame}: ${array.layer} holds ${array.length} items, and ${received} were recorded. A page script may have replaced ${array.layer}.push or the array.`
5913
+ });
5914
+ }
5915
+ }
5916
+ return flags2;
5917
+ }
5918
+
5535
5919
  // packages/recorder/src/gtm-override.ts
5536
5920
  import { getDomain as getDomain2 } from "tldts";
5537
5921
  var GTM_ORIGIN = "https://www.googletagmanager.com";
@@ -5580,31 +5964,31 @@ function parseGtmOverride(input) {
5580
5964
  return result;
5581
5965
  }
5582
5966
  function parseLoader(input) {
5583
- const bad = (m) => new GtmOverrideError(m);
5967
+ const bad2 = (m) => new GtmOverrideError(m);
5584
5968
  if (typeof input !== "object" || input === null || Array.isArray(input)) {
5585
- throw bad('loader must be an object like {"replace": "<script URL>"} or {"match": "<regex>"}');
5969
+ throw bad2('loader must be an object like {"replace": "<script URL>"} or {"match": "<regex>"}');
5586
5970
  }
5587
5971
  const l = input;
5588
- if (Object.keys(l).some((k) => k !== "replace" && k !== "match")) throw bad("loader has unknown fields. Allowed: replace, match");
5589
- if (l.replace === void 0 && l.match === void 0) throw bad("loader needs replace (a script URL) or match (a regex)");
5972
+ if (Object.keys(l).some((k) => k !== "replace" && k !== "match")) throw bad2("loader has unknown fields. Allowed: replace, match");
5973
+ if (l.replace === void 0 && l.match === void 0) throw bad2("loader needs replace (a script URL) or match (a regex)");
5590
5974
  const result = {};
5591
5975
  if (l.replace !== void 0) {
5592
- if (typeof l.replace !== "string") throw bad("loader.replace must be a script URL");
5976
+ if (typeof l.replace !== "string") throw bad2("loader.replace must be a script URL");
5593
5977
  let url;
5594
5978
  try {
5595
5979
  url = new URL(l.replace);
5596
5980
  } catch {
5597
- throw bad("loader.replace must be an absolute http or https URL");
5981
+ throw bad2("loader.replace must be an absolute http or https URL");
5598
5982
  }
5599
- if (url.protocol !== "http:" && url.protocol !== "https:") throw bad("loader.replace must be an absolute http or https URL");
5983
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw bad2("loader.replace must be an absolute http or https URL");
5600
5984
  result.replace = url.href;
5601
5985
  }
5602
5986
  if (l.match !== void 0) {
5603
- if (typeof l.match !== "string" || l.match === "") throw bad("loader.match must be a non-empty regular expression string");
5987
+ if (typeof l.match !== "string" || l.match === "") throw bad2("loader.match must be a non-empty regular expression string");
5604
5988
  try {
5605
5989
  new RegExp(l.match);
5606
5990
  } catch {
5607
- throw bad("loader.match is not a valid regular expression");
5991
+ throw bad2("loader.match is not a valid regular expression");
5608
5992
  }
5609
5993
  result.match = l.match;
5610
5994
  }
@@ -5612,15 +5996,15 @@ function parseLoader(input) {
5612
5996
  }
5613
5997
  function parseTestGtmOrigin(value) {
5614
5998
  if (value === void 0 || value === "") return void 0;
5615
- const bad = () => new GtmOverrideError(`${TEST_GTM_ORIGIN_ENV} must be http://localhost, http://127.0.0.1 or http://[::1], with an optional port and nothing else`);
5999
+ const bad2 = () => new GtmOverrideError(`${TEST_GTM_ORIGIN_ENV} must be http://localhost, http://127.0.0.1 or http://[::1], with an optional port and nothing else`);
5616
6000
  let url;
5617
6001
  try {
5618
6002
  url = new URL(value);
5619
6003
  } catch {
5620
- throw bad();
6004
+ throw bad2();
5621
6005
  }
5622
6006
  const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
5623
- if (url.protocol !== "http:" || !loopback || /[?#@]/.test(value) || url.username || url.password || url.pathname !== "/") throw bad();
6007
+ if (url.protocol !== "http:" || !loopback || /[?#@]/.test(value) || url.username || url.password || url.pathname !== "/") throw bad2();
5624
6008
  return url.origin;
5625
6009
  }
5626
6010
  function isGtmJsUrl(url) {
@@ -5749,11 +6133,11 @@ function gtmFailureMessage(override, applied, fetchError, hint = "") {
5749
6133
  if (applied.length === 0) {
5750
6134
  return `no container request matched: the page never requested https://www.googletagmanager.com/gtm.js?id=${container}, a Stape-style loader for it${replace ? `, or ${replace}` : ""}, and no loader script held the container${hint}`;
5751
6135
  }
5752
- const bad = applied.find((a) => a.status !== 200);
5753
- if (bad) {
5754
- if (bad.status === 0) return `the preview build of ${container} could not be fetched${fetchError ? `: ${fetchError}` : ""}`;
5755
- const note = bad.status === 404 ? " (the environment may have no version)" : "";
5756
- return `the preview build of ${container} returned status ${bad.status}${note}`;
6136
+ const bad2 = applied.find((a) => a.status !== 200);
6137
+ if (bad2) {
6138
+ if (bad2.status === 0) return `the preview build of ${container} could not be fetched${fetchError ? `: ${fetchError}` : ""}`;
6139
+ const note = bad2.status === 404 ? " (the environment may have no version)" : "";
6140
+ return `the preview build of ${container} returned status ${bad2.status}${note}`;
5757
6141
  }
5758
6142
  if (replace && !applied.some((a) => a.way === "replace")) return `loader.replace was set but the page never requested ${replace}`;
5759
6143
  return void 0;
@@ -5779,19 +6163,23 @@ function loaderLayerName(req) {
5779
6163
  const real = unwrapStapeLoader(req);
5780
6164
  return real ? loaderName(real.url, false) : void 0;
5781
6165
  }
6166
+ var MAX_LISTED_NAMES = 5;
5782
6167
  function buildDataLayerNotHookedFlag(input) {
5783
6168
  const hooked = /* @__PURE__ */ new Set([DEFAULT_DATALAYER, ...input.hooked]);
5784
6169
  const misses = input.loaders.filter((l) => !hooked.has(l.name));
5785
- const first = misses[0];
5786
- if (!first) return void 0;
5787
- const shown2 = isDataLayerName(first.name) && !isValueSegment(first.name) ? `"${first.name}"` : "(other)";
6170
+ if (misses.length === 0) return void 0;
6171
+ const names = [...new Set(misses.map((m) => isDataLayerName(m.name) && !isValueSegment(m.name) ? `"${m.name}"` : "(other)"))];
6172
+ const listed = names.slice(0, MAX_LISTED_NAMES).join(", ");
6173
+ const rest = names.length - MAX_LISTED_NAMES;
6174
+ const shown2 = rest > 0 ? `${listed} and ${rest} more` : listed;
6175
+ const plural2 = names.length > 1;
5788
6176
  return {
5789
6177
  type: "flag",
5790
6178
  id: newId("flag"),
5791
6179
  runId: input.runId,
5792
6180
  kind: "dataLayerNotHooked",
5793
6181
  recordIds: misses.map((m) => m.id),
5794
- detail: `A Google loader names the data layer ${shown2}, which is not hooked, so pushes to it are not recorded. Add it to options.dataLayerNames.`
6182
+ detail: plural2 ? `Google loaders name the data layers ${shown2}, which are not hooked, so pushes to them are not recorded. Add them to options.dataLayerNames.` : `A Google loader names the data layer ${shown2}, which is not hooked, so pushes to it are not recorded. Add it to options.dataLayerNames.`
5795
6183
  };
5796
6184
  }
5797
6185
 
@@ -5806,35 +6194,57 @@ var MAX_NAME = 256;
5806
6194
  var CONTAINER2 = /^GTM-[A-Z0-9]+$/;
5807
6195
  var TAG_ID2 = /^[0-9]+$/;
5808
6196
  var isBad = (value) => typeof value === "object" && value !== null && "bad" in value;
6197
+ function typeClass(value) {
6198
+ if (value === null) return "null";
6199
+ if (Array.isArray(value)) return "array";
6200
+ const type = typeof value;
6201
+ return type === "string" || type === "number" || type === "boolean" || type === "undefined" ? type : "object";
6202
+ }
6203
+ var bad = (what, value) => ({ bad: what, got: typeClass(value) });
6204
+ function digits(value) {
6205
+ if (typeof value === "number") return Number.isSafeInteger(value) && value >= 0 ? String(value) : null;
6206
+ if (typeof value === "string" && value.length <= MAX_TAG_ID && TAG_ID2.test(value)) return value;
6207
+ return null;
6208
+ }
5809
6209
  function parseTag(raw) {
5810
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return { bad: "tag" };
6210
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return bad("tag", raw);
5811
6211
  const tag = raw;
5812
- if (typeof tag.id !== "string" || tag.id.length > MAX_TAG_ID || !TAG_ID2.test(tag.id)) return { bad: "tagId" };
5813
- if (typeof tag.status !== "string" || tag.status.length > MAX_STATUS) return { bad: "tagStatus" };
6212
+ const id = digits(tag.id);
6213
+ if (id === null) return bad("tagId", tag.id);
6214
+ if (typeof tag.status !== "string" || tag.status.length > MAX_STATUS) return bad("tagStatus", tag.status);
5814
6215
  const time = tag.executionTime ?? null;
5815
- if (time !== null && (typeof time !== "number" || !Number.isFinite(time))) return { bad: "executionTime" };
6216
+ if (time !== null && (typeof time !== "number" || !Number.isFinite(time))) return bad("executionTime", time);
5816
6217
  const name = tag.name ?? null;
5817
- if (name !== null && (typeof name !== "string" || name.length > MAX_NAME)) return { bad: "tagName" };
5818
- return { id: tag.id, name, status: tag.status, executionTime: time };
6218
+ if (name !== null && (typeof name !== "string" || name.length > MAX_NAME)) return bad("tagName", name);
6219
+ return { id, name, status: tag.status, executionTime: time };
5819
6220
  }
5820
6221
  function parseTagReport(payload, side, ctx) {
5821
- const fail = (what) => ({
6222
+ const fail = (what, got) => ({
5822
6223
  ok: false,
5823
- invalid: { type: "invalidReport", id: newId("collectorReport"), runId: ctx.runId, t: ctx.t, error: `tagReport:${what}`, body: "" }
6224
+ invalid: {
6225
+ type: "invalidReport",
6226
+ id: newId("collectorReport"),
6227
+ runId: ctx.runId,
6228
+ t: ctx.t,
6229
+ error: `tagReport:${what}`,
6230
+ got,
6231
+ body: ""
6232
+ }
5824
6233
  });
5825
- if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return fail("payload");
6234
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return fail("payload", typeClass(payload));
5826
6235
  const p = payload;
5827
- if (typeof p.container !== "string" || !CONTAINER2.test(p.container)) return fail("container");
5828
- if (typeof p.event !== "string" || p.event.length > MAX_EVENT) return fail("event");
6236
+ if (typeof p.container !== "string" || !CONTAINER2.test(p.container)) return fail("container", typeClass(p.container));
6237
+ if (typeof p.event !== "string" || p.event.length > MAX_EVENT) return fail("event", typeClass(p.event));
5829
6238
  const uniqueId = p.gtmUniqueEventId ?? null;
5830
- if (uniqueId !== null && (typeof uniqueId !== "number" || !Number.isFinite(uniqueId))) return fail("gtmUniqueEventId");
5831
- const version = p.version ?? null;
5832
- if (version !== null && (typeof version !== "string" || version.length > MAX_VERSION)) return fail("version");
5833
- if (!Array.isArray(p.tags) || p.tags.length > MAX_TAGS) return fail("tags");
6239
+ if (uniqueId !== null && (typeof uniqueId !== "number" || !Number.isFinite(uniqueId))) return fail("gtmUniqueEventId", typeClass(uniqueId));
6240
+ const rawVersion = p.version ?? null;
6241
+ const version = typeof rawVersion === "number" ? digits(rawVersion) : typeof rawVersion === "string" && rawVersion.length <= MAX_VERSION ? rawVersion : null;
6242
+ if (rawVersion !== null && version === null) return fail("version", typeClass(rawVersion));
6243
+ if (!Array.isArray(p.tags) || p.tags.length > MAX_TAGS) return fail("tags", typeClass(p.tags));
5834
6244
  const tags = [];
5835
6245
  for (const raw of p.tags) {
5836
6246
  const tag = parseTag(raw);
5837
- if (isBad(tag)) return fail(tag.bad);
6247
+ if (isBad(tag)) return fail(tag.bad, tag.got);
5838
6248
  tags.push(tag);
5839
6249
  }
5840
6250
  const report = {
@@ -7359,6 +7769,8 @@ var unloadInitScript = `(() => {
7359
7769
  // packages/recorder/src/recorder.ts
7360
7770
  var TAGREEVE_VERSION = readVersion();
7361
7771
  var REDACTED_VALUE = "[redacted]";
7772
+ var TALLY_DEADLINE_MS = 2e3;
7773
+ var TALLY_POSTED_WAIT_MS = 1e3;
7362
7774
  var TAG_REPORT_QUIET_MS = 500;
7363
7775
  var TAG_REPORT_MAX_WAIT_MS = 2500;
7364
7776
  function redactRefererQuery(headers) {
@@ -7429,6 +7841,8 @@ var Recorder = class _Recorder {
7429
7841
  selfRecorded = /* @__PURE__ */ new WeakSet();
7430
7842
  responses = [];
7431
7843
  dataLayerEvents = [];
7844
+ dataLayerReassigns = [];
7845
+ payloadCounts = new PayloadCounts();
7432
7846
  eventFrames = /* @__PURE__ */ new Map();
7433
7847
  frameNumbers = /* @__PURE__ */ new WeakMap();
7434
7848
  frameNavigations = /* @__PURE__ */ new WeakMap();
@@ -7546,9 +7960,16 @@ var Recorder = class _Recorder {
7546
7960
  };
7547
7961
  await context.exposeBinding(DATALAYER_BINDING, (source, payload) => {
7548
7962
  const isMain = source.frame === source.page.mainFrame();
7963
+ if (payload?.reassigned) {
7964
+ if (typeof payload.t === "number") this.dataLayerReassigns.push({ n: this.frameNumber(source.frame), doc: this.frameDocumentId(source.frame), t: pageTimeToEpoch(payload.t, this.clockOffset) });
7965
+ return;
7966
+ }
7967
+ this.payloadCounts.add(payload ?? {}, this.frameNumber(source.frame), hookedLayerNames(this.options.dataLayerNames));
7549
7968
  const event = dataLayerEventFromPayload(payload, this.runId, this.clockOffset, { main: isMain, n: this.frameNumber(source.frame) });
7550
7969
  if (!event) return;
7551
- this.dataLayerEvents.push({ ...event, stepId: this.currentStepId });
7970
+ let at = this.dataLayerEvents.length;
7971
+ while (at > 0 && this.dataLayerEvents[at - 1].t > event.t) at--;
7972
+ this.dataLayerEvents.splice(at, 0, { ...event, stepId: this.currentStepId });
7552
7973
  if (!isMain) this.eventFrames.set(event.id, { id: this.frameDocumentId(source.frame), url: source.frame.url() });
7553
7974
  });
7554
7975
  await context.addInitScript(dataLayerInitScript(this.options.dataLayerNames));
@@ -8140,11 +8561,62 @@ var Recorder = class _Recorder {
8140
8561
  }
8141
8562
  async flushUnloadQueues() {
8142
8563
  const script = `window.${UNLOAD_FLUSH}?.()`;
8143
- for (const page2 of this.context.pages()) {
8144
- await page2.evaluate(script).catch(() => void 0);
8145
- }
8564
+ let timer;
8565
+ const deadline = new Promise((resolve5) => {
8566
+ timer = setTimeout(resolve5, TALLY_DEADLINE_MS);
8567
+ });
8568
+ const flushing = Promise.all(this.context.pages().map((page2) => page2.evaluate(script).catch(() => void 0)));
8569
+ await Promise.race([flushing, deadline]);
8570
+ clearTimeout(timer);
8146
8571
  await this.wait(50);
8147
8572
  }
8573
+ /** Asks each open frame how many items its hooked arrays hold, so a gap against the records can be flagged. */
8574
+ async collectTallies() {
8575
+ const names = hookedLayerNames(this.options.dataLayerNames);
8576
+ const tallies = [];
8577
+ let frames = [];
8578
+ try {
8579
+ frames = this.context.pages().flatMap((page2) => page2.frames());
8580
+ } catch {
8581
+ return tallies;
8582
+ }
8583
+ const script = `window.${DATALAYER_TALLY}?.()`;
8584
+ const asking = frames.map(async (frame) => {
8585
+ try {
8586
+ const tally = validateTally(this.frameNumber(frame), await frame.evaluate(script), names);
8587
+ if (tally) tallies.push(tally);
8588
+ } catch {
8589
+ }
8590
+ });
8591
+ let timer;
8592
+ const deadline = new Promise((resolve5) => {
8593
+ timer = setTimeout(resolve5, TALLY_DEADLINE_MS);
8594
+ });
8595
+ await Promise.race([Promise.all(asking), deadline]);
8596
+ clearTimeout(timer);
8597
+ return [...tallies];
8598
+ }
8599
+ async tallyDataLayers() {
8600
+ const tallies = await this.collectTallies();
8601
+ const start = Date.now();
8602
+ while (postedAhead(tallies, this.payloadCounts) && Date.now() - start < TALLY_POSTED_WAIT_MS) await this.wait(20);
8603
+ return buildTallyFlags(this.runId, tallies, this.payloadCounts);
8604
+ }
8605
+ dataLayerReassignedFlags(requests) {
8606
+ const loaders = requests.filter((r) => isGoogleLoaderUrl(r.url));
8607
+ if (loaders.length === 0) return [];
8608
+ const frames = new Set(
8609
+ this.dataLayerReassigns.filter((r) => loaders.some((l) => this.requestFrameIds.get(l.id) === r.doc && l.t <= r.t)).map((r) => r.n)
8610
+ );
8611
+ return [...frames].sort((a, b) => a - b).map((n) => ({
8612
+ type: "flag",
8613
+ id: newId("flag"),
8614
+ runId: this.runId,
8615
+ kind: "dataLayerReassigned",
8616
+ recordIds: [],
8617
+ detail: `Frame ${n} replaced window.dataLayer with a new array after a Google loader request. Pushes to the new array are still recorded.`
8618
+ }));
8619
+ }
8148
8620
  noteContainerExit() {
8149
8621
  if (this.session?.containerExited() && !this.containerFailure) {
8150
8622
  this.containerFailure = { errorClass: "exited", message: "The server container ended during the run." };
@@ -8159,14 +8631,15 @@ var Recorder = class _Recorder {
8159
8631
  async close() {
8160
8632
  const closeStartedAt = nodeNow();
8161
8633
  this.noteContainerExit();
8634
+ await this.waitForLateTagReports();
8162
8635
  if (this.options.networkMode !== "live") await this.flushUnloadQueues();
8636
+ const tallyFlags = await this.tallyDataLayers();
8163
8637
  if (this.session) {
8164
8638
  const session = this.session;
8165
8639
  await waitForQuiet(() => session.lastCallAt());
8166
8640
  session.stopRecording();
8167
8641
  this.noteContainerExit();
8168
8642
  }
8169
- await this.waitForLateTagReports();
8170
8643
  this.closed = true;
8171
8644
  try {
8172
8645
  await this.browser.close();
@@ -8208,8 +8681,10 @@ var Recorder = class _Recorder {
8208
8681
  } else if (!netLog) {
8209
8682
  flags2.push({ type: "flag", id: newId("flag"), runId: this.runId, kind: "netLogUnreadable", recordIds: [], detail: "The net log could not be read, so requests sent while a frame unloads may be missing." });
8210
8683
  }
8684
+ flags2.push(...this.dataLayerReassignedFlags(requests));
8211
8685
  const notHooked = buildDataLayerNotHookedFlag({ runId: this.runId, loaders: this.loaderLayers, hooked: this.options.dataLayerNames ?? [] });
8212
8686
  if (notHooked) flags2.push(notHooked);
8687
+ flags2.push(...tallyFlags);
8213
8688
  this.recordServerContainer(requests, hits, containerCounts, flags2);
8214
8689
  const consentEpochs = this.buildConsentEpochs();
8215
8690
  let records = {
@@ -8266,6 +8741,14 @@ function abortCode(error) {
8266
8741
  return "failed";
8267
8742
  }
8268
8743
  var BODY_HEADERS = /* @__PURE__ */ new Set(["content-type", "content-length", "content-encoding", "content-language", "content-location", "origin"]);
8744
+ function isGoogleLoaderUrl(url) {
8745
+ try {
8746
+ const u = new URL(url);
8747
+ return u.hostname === "www.googletagmanager.com" && (u.pathname === "/gtm.js" || u.pathname === "/gtag/js");
8748
+ } catch {
8749
+ return false;
8750
+ }
8751
+ }
8269
8752
  function withoutMethodChangeHeaders(headers) {
8270
8753
  return Object.fromEntries(Object.entries(headers).filter(([name]) => !BODY_HEADERS.has(name.toLowerCase())));
8271
8754
  }
@@ -8620,15 +9103,13 @@ async function fillVerified(element, field, cardHost, value, timeout, typed) {
8620
9103
  await handle.fill(value, { timeout: tryMs() });
8621
9104
  return;
8622
9105
  } catch (error) {
8623
- if (!(error instanceof Error && error.name === "TimeoutError")) {
8624
- if (error instanceof OwnReason) throw error;
8625
- const moved = (await frameStillServed(element, cardHost, field)).url() !== checkedUrl;
8626
- const attached = handle ? await handle.evaluate((e) => e.isConnected).catch(() => false) : true;
8627
- if (moved || !attached) throw new OwnReason(GONE_FRAME);
8628
- throw error;
8629
- }
8630
- if (Date.now() >= deadline) throw error;
8631
- continue;
9106
+ const timedOut = error instanceof Error && error.name === "TimeoutError";
9107
+ if (error instanceof OwnReason) throw error;
9108
+ if (timedOut && Date.now() < deadline) continue;
9109
+ const moved = (await frameStillServed(element, cardHost, field)).url() !== checkedUrl;
9110
+ const attached = handle ? await handle.evaluate((e) => e.isConnected).catch(() => false) : true;
9111
+ if (moved || !attached) throw new OwnReason(GONE_FRAME);
9112
+ throw error;
8632
9113
  }
8633
9114
  }
8634
9115
  if (Date.now() >= deadline) {
@@ -8743,8 +9224,12 @@ function resolveSitePath(path, site, vars) {
8743
9224
  if (url.origin !== base2.origin) throw new Error(`"${path}" leaves the site ${base2.origin}`);
8744
9225
  return url.href;
8745
9226
  }
8746
- async function stdinResolver(_message, signal) {
8747
- const rl = createInterface2({ input: process.stdin, output: process.stdout });
9227
+ var stderrPrint = (text2) => {
9228
+ process.stderr.write(`${text2}
9229
+ `);
9230
+ };
9231
+ async function stdinResolver(_message, signal, streams = { input: process.stdin, output: process.stderr }) {
9232
+ const rl = createInterface2(streams);
8748
9233
  try {
8749
9234
  await rl.question("Press Enter when done. ", { signal });
8750
9235
  } catch (error) {
@@ -8963,7 +9448,7 @@ async function runStep(step, recorder, scenario, identity, options, record) {
8963
9448
  return;
8964
9449
  case "wait":
8965
9450
  if (typeof step.value === "number") await recorder.wait(step.value);
8966
- else if ("url" in step.value) await waitForUrl(recorder, step.value.url, timeout);
9451
+ else if ("url" in step.value) await waitForUrl(recorder, step.value.url, step.value.timeout ?? timeout);
8967
9452
  else {
8968
9453
  const deadline = Date.now() + timeout;
8969
9454
  const target = await locate(page2, recorder, step.value.selector, record, timeout);
@@ -8983,8 +9468,7 @@ async function runStep(step, recorder, scenario, identity, options, record) {
8983
9468
  await runPayment(page2, recorder, step.value, identity, options.testPayment, record, timeout, new URL(recorder.site).hostname);
8984
9469
  return;
8985
9470
  case "handoff": {
8986
- const print = options.print ?? ((text2) => process.stdout.write(`${text2}
8987
- `));
9471
+ const print = options.print ?? stderrPrint;
8988
9472
  print(`
8989
9473
  Handoff: ${step.value}
8990
9474
  ${HANDOFF_REMINDER}
@@ -9325,7 +9809,7 @@ var OPTIONS = {
9325
9809
  version: { type: "boolean" },
9326
9810
  help: { type: "boolean", short: "h" }
9327
9811
  };
9328
- function commandOf(argv) {
9812
+ function commandOf2(argv) {
9329
9813
  const { tokens } = parseArgs({ args: argv, allowPositionals: true, strict: false, options: OPTIONS, tokens: true });
9330
9814
  const isCommand = (word) => COMMANDS.includes(word);
9331
9815
  let skip = false;
@@ -9346,7 +9830,7 @@ function parseCli(argv) {
9346
9830
  return parseCommand(argv);
9347
9831
  } catch (error) {
9348
9832
  if (error instanceof UsageError && error.command === void 0) {
9349
- const command = commandOf(argv);
9833
+ const command = commandOf2(argv);
9350
9834
  if (command !== void 0) error.command = command;
9351
9835
  }
9352
9836
  throw error;
@@ -9377,6 +9861,7 @@ function parseCommand(argv) {
9377
9861
  if (values.help && command !== void 0 && COMMANDS.includes(command)) {
9378
9862
  return { command: "help", topic: command };
9379
9863
  }
9864
+ if (command === void 0 && !values.help && Object.keys(values).length) throw new UsageError("Give a command before the options.");
9380
9865
  if (values.help || command === void 0) return { command: "help" };
9381
9866
  if (values["across-frames"] && command !== "diff") throw new UsageError("--across-frames is only for diff.");
9382
9867
  if (values["event-map"] !== void 0 && command !== "diff") throw new UsageError("--event-map is only for diff.");
@@ -9387,7 +9872,9 @@ function parseCommand(argv) {
9387
9872
  return { command: "init", json: values.json ?? false };
9388
9873
  }
9389
9874
  if (command === "template") {
9390
- if (rest[0] !== "web" || rest.length !== 1) throw new UsageError("template needs a name: web");
9875
+ if (rest.length === 0) throw new UsageError("template needs a name: web");
9876
+ if (rest[0] !== "web") throw new UsageError("Unknown template name. web is the only name.");
9877
+ if (rest.length !== 1) throw new UsageError("template web takes no further arguments.");
9391
9878
  const other = Object.keys(values).find((key) => key !== "json");
9392
9879
  if (other) throw new UsageError(`template does not take --${other}.`);
9393
9880
  return { command: "template", name: "web", json: values.json ?? false };
@@ -9548,7 +10035,7 @@ function flagChangeLabel(f) {
9548
10035
  return `${f.host ? `${f.kind} ${f.host}` : f.kind}: ${f.a} -> ${f.b}`;
9549
10036
  }
9550
10037
  function describePushDiff(d) {
9551
- const at = (r) => `[epoch ${r.epoch}, frame ${r.frame}]`;
10038
+ const at = (r) => `[epoch ${r.epoch}, frame ${r.frame}${r.kind === void 0 ? "" : `, kind ${r.kind}`}]`;
9552
10039
  return [
9553
10040
  ...d.eventsRemoved.map((r) => `removed event ${r.event} ${at(r)}`),
9554
10041
  ...d.eventsAdded.map((r) => `new event ${r.event} ${at(r)}`),
@@ -9815,7 +10302,7 @@ function validKey(k) {
9815
10302
  }
9816
10303
  var FRAME_KINDS = /* @__PURE__ */ new Set(["main", "embedded", "unknown"]);
9817
10304
  function validPushGroup(g) {
9818
- return isRecord2(g) && typeof g.epoch === "string" && typeof g.event === "string" && typeof g.frame === "string" && FRAME_KINDS.has(g.frame) && Array.isArray(g.paths) && g.paths.every((p) => isRecord2(p) && typeof p.path === "string" && isStringArray(p.types));
10305
+ return isRecord2(g) && typeof g.epoch === "string" && typeof g.event === "string" && (g.kind === void 0 || g.kind === "gtag" || g.kind === "object") && typeof g.frame === "string" && FRAME_KINDS.has(g.frame) && Array.isArray(g.paths) && g.paths.every((p) => isRecord2(p) && typeof p.path === "string" && isStringArray(p.types));
9819
10306
  }
9820
10307
  function parseBaseline(text2, label) {
9821
10308
  let json;
@@ -9833,7 +10320,7 @@ function parseBaseline(text2, label) {
9833
10320
  throw new BaselineError(`${label} is not a valid baseline file`, "invalid");
9834
10321
  }
9835
10322
  if (json.dataLayer !== void 0 && !(Array.isArray(json.dataLayer) && json.dataLayer.every(validPushGroup))) {
9836
- throw new BaselineError(`${label} is not a valid baseline file`, "invalid");
10323
+ throw new BaselineError(`${label} has an invalid dataLayer section`, "invalid");
9837
10324
  }
9838
10325
  return json;
9839
10326
  }
@@ -9878,9 +10365,8 @@ function defaultBaselineName(run) {
9878
10365
  }
9879
10366
  const unsafe = (part) => /[/\\\0]/.test(part) || part.includes("..") || part.startsWith(".");
9880
10367
  const name = scenarioName(run.scenario);
9881
- if (!name || unsafe(name) || unsafe(run.store ?? "") || unsafe(run.variant ?? "") || run.store !== void 0 && !STORE_NAME.test(run.store) || run.variant !== void 0 && !VARIANT_NAME2.test(run.variant)) {
9882
- throw new BaselineError("The scenario, store or variant in this record cannot name a baseline file. Give the baseline path.", "usage");
9883
- }
10368
+ 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_NAME2.test(run.variant) ? "variant" : void 0;
10369
+ if (bad2) throw new BaselineError(`The ${bad2} in this record cannot name a baseline file. Give the baseline path.`, "usage");
9884
10370
  return baselineFileName(run.scenario, run.store, run.variant);
9885
10371
  }
9886
10372
  var VARIANT_NAME2 = /^[a-z0-9][a-z0-9_-]*$/;
@@ -9903,6 +10389,10 @@ function compareBaseline(baseline, records) {
9903
10389
  } else {
9904
10390
  const pushes = diffPushes(baseline.dataLayer, pushGroups(records), { epochOrder: epochOrder2 });
9905
10391
  warnings.push(...describePushDiff(pushes).map((line) => `dataLayer ${line}`));
10392
+ warnings.push(...pushes.kindChanged.map((k) => `dataLayer push kind changed: ${k.event}`));
10393
+ if (baseline.dataLayer.some((g) => g.kind === void 0)) {
10394
+ warnings.push("dataLayer push kinds not compared: the baseline was saved by 0.6.0-rc.2. Save it again to compare them.");
10395
+ }
9906
10396
  }
9907
10397
  return {
9908
10398
  drift: diff.drift,
@@ -9913,6 +10403,7 @@ function compareBaseline(baseline, records) {
9913
10403
  changes: describeDiff(diff)
9914
10404
  };
9915
10405
  }
10406
+ var errnoCode = (error) => error.code ?? "unknown error";
9916
10407
  async function baselineCommand(args, io) {
9917
10408
  let records;
9918
10409
  try {
@@ -9928,19 +10419,26 @@ async function baselineCommand(args, io) {
9928
10419
  const baseline = buildBaseline(records, args.byPage);
9929
10420
  let output = args.output;
9930
10421
  if (output === void 0) {
9931
- output = join7(DEFAULT_BASELINES, defaultBaselineName(records.run));
9932
- if (!insideBaselines(output)) throw new BaselineError("The baseline path leaves tagreeve/baselines. Give the baseline path.", "usage");
9933
- await mkdir2(DEFAULT_BASELINES, { recursive: true });
9934
- }
9935
- if (args.output !== void 0) {
9936
10422
  try {
9937
- await mkdir2(dirname3(output), { recursive: true });
10423
+ output = join7(DEFAULT_BASELINES, defaultBaselineName(records.run));
9938
10424
  } catch (error) {
9939
- throw new BaselineError(`Cannot make the folder for ${args.output}: ${error.code ?? "unknown error"}`, "usage");
10425
+ if (error instanceof BaselineError) throw new BaselineError(`${args.input}: ${error.message}`, error.code);
10426
+ throw error;
9940
10427
  }
10428
+ if (!insideBaselines(output)) throw new BaselineError(`${args.input}: the baseline path leaves tagreeve/baselines. Give the baseline path.`, "usage");
9941
10429
  }
9942
- await writeFile2(output, `${JSON.stringify(baseline, null, 2)}
10430
+ const shown2 = args.output ?? output;
10431
+ try {
10432
+ await mkdir2(dirname3(output), { recursive: true });
10433
+ } catch (error) {
10434
+ throw new BaselineError(`Cannot make the folder for ${shown2}: ${errnoCode(error)}`, "usage");
10435
+ }
10436
+ try {
10437
+ await writeFile2(output, `${JSON.stringify(baseline, null, 2)}
9943
10438
  `);
10439
+ } catch (error) {
10440
+ throw new BaselineError(`Cannot write ${shown2}: ${errnoCode(error)}`, "usage");
10441
+ }
9944
10442
  const hits = baseline.keys.reduce((n, k) => n + k.tuples.reduce((m, t) => m + t.count, 0), 0);
9945
10443
  io.stdout(`Baseline ${output}: ${baseline.keys.length} keys, ${hits} hits
9946
10444
  `);
@@ -9956,7 +10454,7 @@ import { execFile as execFile2 } from "node:child_process";
9956
10454
  import { stat as stat3 } from "node:fs/promises";
9957
10455
  import { dirname as dirname4, join as join8, resolve as resolve3 } from "node:path";
9958
10456
  var GIT_TIMEOUT_MS = 5e3;
9959
- var PROBE_FILE = "probe.jsonl";
10457
+ var PROBE_FILE = "run_probe.jsonl";
9960
10458
  async function nearestExistingDir(path) {
9961
10459
  let dir = resolve3(path);
9962
10460
  for (; ; ) {
@@ -9978,10 +10476,11 @@ function checkIgnoreExit(cwd, path) {
9978
10476
  });
9979
10477
  });
9980
10478
  }
9981
- async function gitIgnoreStatus(path) {
10479
+ async function gitIgnoreStatus(path, options = {}) {
9982
10480
  const absolute = resolve3(path);
9983
10481
  const existing = await nearestExistingDir(absolute);
9984
- const code = await checkIgnoreExit(existing, join8(absolute, PROBE_FILE));
10482
+ const target = options.probe === "folder" ? `${absolute}/` : join8(absolute, PROBE_FILE);
10483
+ const code = await checkIgnoreExit(existing, target);
9985
10484
  return code === 0 ? "ignored" : code === 1 ? "unignored" : "unknown";
9986
10485
  }
9987
10486
  async function isUnignoredInWorkTree(path) {
@@ -10021,14 +10520,16 @@ async function ensureIgnoreLine(cwd) {
10021
10520
  current = void 0;
10022
10521
  }
10023
10522
  if (current?.split(/\r?\n/).some((line) => line.trim() === IGNORE_LINE)) return { path: ".gitignore", action: "skipped", text: `Skipped .gitignore: it already has ${IGNORE_LINE}` };
10024
- if (await gitIgnoreStatus(join9(cwd, "tagreeve/runs")) === "ignored") return { path: ".gitignore", action: "skipped", text: "Skipped .gitignore: git already ignores tagreeve/runs/" };
10523
+ if (await gitIgnoreStatus(join9(cwd, "tagreeve/runs"), { probe: "folder" }) === "ignored") return { path: ".gitignore", action: "skipped", text: "Skipped .gitignore: git already ignores tagreeve/runs/" };
10025
10524
  const prefix = current === void 0 || current === "" || current.endsWith("\n") ? "" : "\n";
10026
10525
  await appendFile(file, `${prefix}${IGNORE_LINE}
10027
10526
  `);
10028
10527
  return current === void 0 ? { path: ".gitignore", action: "created", text: `Created .gitignore with ${IGNORE_LINE}` } : { path: ".gitignore", action: "added", text: `Added ${IGNORE_LINE} to .gitignore` };
10029
10528
  }
10030
10529
  async function ensureFolder(cwd, folder) {
10031
- if (await exists(join9(cwd, folder))) return { path: `${folder}/`, action: "skipped", text: `Skipped ${folder}/: it exists` };
10530
+ const found = await stat4(join9(cwd, folder)).catch(() => void 0);
10531
+ if (found && !found.isDirectory()) throw Object.assign(new Error("not a folder"), { code: "NOTFOLDER" });
10532
+ if (found) return { path: `${folder}/`, action: "skipped", text: `Skipped ${folder}/: it exists` };
10032
10533
  await mkdir3(join9(cwd, folder), { recursive: true });
10033
10534
  return { path: `${folder}/`, action: "created", text: `Created ${folder}/` };
10034
10535
  }
@@ -10040,6 +10541,8 @@ async function ensureConfig(cwd) {
10040
10541
  }
10041
10542
  function failureText(path, error) {
10042
10543
  const code = error?.code;
10544
+ if (code === "NOTFOLDER") return `${path.replace(/\/$/, "")} is not a folder
10545
+ `;
10043
10546
  const reason = code === "EACCES" || code === "EPERM" ? "permission denied" : code === "EEXIST" ? "it exists" : code === "ENOTDIR" || code === "EISDIR" ? "a file or folder is in the way" : "the write failed";
10044
10547
  return `Could not write ${path}: ${reason}
10045
10548
  `;
@@ -10058,6 +10561,8 @@ async function initCommand(io, json = false, cwd = process.cwd()) {
10058
10561
  if (!json) io.stdout(`${item.text}
10059
10562
  `);
10060
10563
  } catch (error) {
10564
+ if (json) io.stdout(`${JSON.stringify({ items: items.map(({ path: path2, action }) => ({ path: path2, action })) })}
10565
+ `);
10061
10566
  io.stderr(failureText(path, error));
10062
10567
  return 2;
10063
10568
  }
@@ -10089,6 +10594,7 @@ var WEB_STEPS = [
10089
10594
  'Add one tag of that type with the trigger in "setup.trigger" (a custom event trigger on the event name ".*" with regex matching on) and the consent setting in "setup.consent".',
10090
10595
  'Turn on "Include tag name" with the key "name" in the Additional Tag Metadata of each tag you want named, or list the names in expectedTags.',
10091
10596
  "Never publish the version.",
10597
+ "The --gtm-override file holds gtmAuth, a secret. Do not print it, and do not keep it in your transcript.",
10092
10598
  "Run Tagreeve with --gtm-override.",
10093
10599
  "Check that tags[<container>].reports in the --json output is greater than 0. An entry with reports 0 and a hint means the install failed."
10094
10600
  ];
@@ -10139,9 +10645,10 @@ var NOTE_TEXT = {
10139
10645
  nestedNameOnly: "a plain name matches a top-level field only; use **.name to match at any depth",
10140
10646
  serverSendProbableLink: "a server container hit is placed by a probable link to a browser hit, which cannot fail a run",
10141
10647
  serverSendUnlinked: "cannot evaluate: a server container hit has no link to a browser hit, so no consent state applies",
10142
- noTagReports: "cannot evaluate: no tag report from this container. Install the reporter: tagreeve template web --json",
10648
+ noTagReports: `cannot evaluate: no tag report from this container. For web tags, install the reporter and run with --gtm-override: ${TAG_REPORTER_HINT}`,
10143
10649
  tagNameUnknown: "cannot evaluate: the tag has no name in its report or in expectedTags"
10144
10650
  };
10651
+ var CANNOT_EVALUATE_NOTES = ["cannotEvaluateBody", "fieldsNotRecorded", "serverSendUnlinked", "noTagReports", "tagNameUnknown"];
10145
10652
  var WORST_FIRST = ["leak", "unchecked", "mixed", "early", "full", "ping"];
10146
10653
  var CONSENT_FIELDS = ["analytics", "ads", "adUserData", "adPersonalization"];
10147
10654
  var MAX_EVIDENCE = 5;
@@ -10204,7 +10711,7 @@ function expectationView(result) {
10204
10711
  kind = "builtin";
10205
10712
  text2 = result.expectation;
10206
10713
  }
10207
- const cannot = !result.pass && (result.note === "cannotEvaluateBody" || result.note === "fieldsNotRecorded" || result.note === "serverSendUnlinked");
10714
+ const cannot = !result.pass && result.note !== void 0 && CANNOT_EVALUATE_NOTES.includes(result.note);
10208
10715
  const status = cannot ? "CANNOT EVALUATE" : result.pass ? "PASS" : severity === "warn" ? "WARN" : "FAIL";
10209
10716
  return {
10210
10717
  status,
@@ -10222,7 +10729,7 @@ var IDENTIFIER_EARLY = "identifiers sent before an answer";
10222
10729
  function namedLeaks(results) {
10223
10730
  const named = /* @__PURE__ */ new Map();
10224
10731
  for (const result of results) {
10225
- if (result.pass || result.note === "cannotEvaluateBody" || result.note === "fieldsNotRecorded" || result.note === "serverSendUnlinked") continue;
10732
+ if (result.pass || result.note !== void 0 && CANNOT_EVALUATE_NOTES.includes(result.note)) continue;
10226
10733
  let label;
10227
10734
  if (result.expectation === "builtin: deniedIdentifiers") label = IDENTIFIER_LEAK;
10228
10735
  else if (result.expectation === "builtin: earlyIdentifiers") label = IDENTIFIER_EARLY;
@@ -10913,7 +11420,7 @@ function formatFlags(flags2) {
10913
11420
  var URL_TOKEN = /[a-z][a-z0-9+.-]*:\/\/\S+/gi;
10914
11421
  var URL_PARTS = /^(?:(?:([a-z][a-z0-9+.-]*:)?\/\/)([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#.*)?$/is;
10915
11422
  var RECEIVED_PAGE = /^(\S+ received )(.+)( as the page)$/s;
10916
- var URL_ENDING_KINDS = /* @__PURE__ */ new Set(["unknownDestination", "firstPartySubdomain", "platformHost", "stubBypass", "possibleRedirectHop"]);
11423
+ var PROSE_KINDS = /* @__PURE__ */ new Set(["possibleRealData", "unloadGap", "netLogUnreadable", "serverContainerFailed", "dataLayerReassigned", "dataLayerNotHooked", "dataLayerIncomplete"]);
10917
11424
  var URL_AT_END = /^(.*?(?:\b[A-Z]+ |: ))((?:[a-z][a-z0-9+.-]*:)?\/\/.*|\/.*)$/s;
10918
11425
  function queryName(pair) {
10919
11426
  const eq = pair.indexOf("=");
@@ -10928,7 +11435,7 @@ function redactUrl(raw) {
10928
11435
  function redactFlagDetail(detail, kind) {
10929
11436
  const page2 = RECEIVED_PAGE.exec(detail);
10930
11437
  if (page2) return `${page2[1]}${redactUrl(page2[2])}${page2[3]}`;
10931
- const tail = URL_ENDING_KINDS.has(kind) ? URL_AT_END.exec(detail) : null;
11438
+ const tail = PROSE_KINDS.has(kind) ? null : URL_AT_END.exec(detail);
10932
11439
  if (tail) return `${tail[1]}${redactUrl(tail[2])}`;
10933
11440
  return detail.replace(URL_TOKEN, redactUrl);
10934
11441
  }
@@ -10965,8 +11472,13 @@ function serverContainerLines(summary) {
10965
11472
  return [`Server container: ${head}${error}; ${calls}; ${c.forwarded} request${c.forwarded === 1 ? "" : "s"} forwarded to Google`, SERVER_CONTAINER_LIMITS];
10966
11473
  }
10967
11474
  var DATALAYER_EVENTS_SHOWN = 3;
11475
+ function dataLayerLabelRank(label) {
11476
+ if (label.startsWith("consent ")) return 1;
11477
+ if (label.startsWith("gtag ")) return 2;
11478
+ return label.startsWith("gtm.") ? 3 : 0;
11479
+ }
10968
11480
  function dataLayerLine({ pushes, steps }) {
10969
- const events = [...new Set(steps.flatMap((s) => s.events.map((e) => e.event)))].filter((e) => e !== NO_EVENT).sort();
11481
+ const events = [...new Set(steps.flatMap((s) => s.events.map((e) => e.event)))].filter((e) => e !== NO_EVENT).sort((a, b) => dataLayerLabelRank(a) - dataLayerLabelRank(b) || (a < b ? -1 : a > b ? 1 : 0));
10970
11482
  const shown2 = events.slice(0, DATALAYER_EVENTS_SHOWN).join(", ");
10971
11483
  const list3 = events.length > 0 ? ` (${shown2}${events.length > DATALAYER_EVENTS_SHOWN ? ", \u2026" : ""})` : "";
10972
11484
  return `dataLayer: ${pushes} push${pushes === 1 ? "" : "es"}, ${events.length} event${events.length === 1 ? "" : "s"}${list3}; shapes in --json`;
@@ -11037,7 +11549,7 @@ function formatSummary(summary) {
11037
11549
  for (const c of b.changes) lines.push(` ${c}`);
11038
11550
  }
11039
11551
  const failed = summary.results.filter((r) => !passesGate(r)).length;
11040
- const warned = summary.results.filter((r) => !r.pass && passesGate(r)).length;
11552
+ const warned = summary.results.filter((r) => !r.pass && passesGate(r)).length + (summary.baseline?.warnings.length ?? 0);
11041
11553
  const warnings = warned > 0 ? ` with ${warned} warning${warned === 1 ? "" : "s"}` : "";
11042
11554
  if (failed === 0 && summary.baseline?.drift) lines.push(`Result: fail (baseline drift)${warnings}`);
11043
11555
  else lines.push(failed === 0 ? `Result: pass${warnings}` : `Result: fail (${failed} of ${summary.results.length})${warnings}`);