#!/usr/bin/env node
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';

const source = await readFile(new URL('../page-guard.js', import.meta.url), 'utf8');

class FakeEvent {
  constructor(type, options = {}) {
    this.type = String(type || '');
    this.cancelable = Boolean(options.cancelable);
    this.defaultPrevented = false;
    this.isTrusted = Boolean(options.isTrusted);
    this.target = options.target || null;
    this.currentTarget = null;
    this._path = Array.isArray(options.path) ? options.path : [];
    this._immediateStopped = false;
    this._propagationStopped = false;
  }
  composedPath() { return [...this._path]; }
  preventDefault() {
    if (this.cancelable) this.defaultPrevented = true;
  }
  stopImmediatePropagation() {
    this._immediateStopped = true;
    this._propagationStopped = true;
  }
  stopPropagation() {
    this._propagationStopped = true;
  }
}

class FakeCustomEvent extends FakeEvent {
  constructor(type, options = {}) {
    super(type, options);
    this.detail = options.detail;
  }
}

const DIRECT_EVENT_PROPERTIES = ['onclick', 'onmousedown', 'onpointerdown', 'onmouseup', 'ontouchstart'];

function installNativeEventHandlerDescriptors(prototype) {
  for (const property of DIRECT_EVENT_PROPERTIES) {
    Object.defineProperty(prototype, property, {
      configurable: true,
      enumerable: true,
      get() {
        return this._directEventHandlers?.get(property) || null;
      },
      set(value) {
        if (!this._directEventHandlers) this._directEventHandlers = new Map();
        if (typeof value === 'function') this._directEventHandlers.set(property, value);
        else this._directEventHandlers.delete(property);
      }
    });
  }
}

class FakeEventTarget {
  constructor() {
    this._listeners = new Map();
    this._directEventHandlers = new Map();
  }
  addEventListener(type, listener, options) {
    if (!listener) return;
    const key = String(type);
    const listeners = this._listeners.get(key) || [];
    listeners.push({ listener, options });
    this._listeners.set(key, listeners);
  }
  removeEventListener(type, listener) {
    const key = String(type);
    const listeners = this._listeners.get(key) || [];
    this._listeners.set(key, listeners.filter(entry => entry.listener !== listener));
  }
  dispatchEvent(event) {
    if (!(event instanceof FakeEvent)) throw new TypeError('Expected FakeEvent');
    if (!event.target) event.target = this;
    event.currentTarget = this;
    const listeners = [...(this._listeners.get(event.type) || [])];
    for (const { listener } of listeners) {
      if (event._immediateStopped) break;
      if (typeof listener === 'function') listener.call(this, event);
      else listener?.handleEvent?.(event);
    }
    if (!event._immediateStopped) {
      const directHandler = this._directEventHandlers.get(`on${event.type}`);
      if (typeof directHandler === 'function') {
        const result = directHandler.call(this, event);
        if (result === false) event.preventDefault();
      }
    }
    return !event.defaultPrevented;
  }
}

class FakeElement extends FakeEventTarget {
  constructor({ tagName = 'DIV', href = '', target = '', rect = {}, style = {}, text = '', attrs = {}, connected = true } = {}) {
    super();
    this.tagName = tagName.toUpperCase();
    this.innerText = text;
    this.textContent = text;
    this.id = attrs.id || '';
    this.className = attrs.class || '';
    this.attributes = new Map(Object.entries(attrs));
    this.isConnected = connected;
    this._href = href;
    this._target = target;
    this._rel = attrs.rel || '';
    this._rect = { width: 120, height: 40, ...rect };
    this._style = {
      position: 'static',
      opacity: '1',
      backgroundColor: 'rgb(20, 20, 20)',
      zIndex: '0',
      display: 'block',
      visibility: 'visible',
      pointerEvents: 'auto',
      ...style
    };
    if (href) this.attributes.set('href', href);
    if (target) this.attributes.set('target', target);
  }
  get href() { return this._href; }
  set href(value) {
    this._href = String(value || '');
    this.attributes.set('href', this._href);
  }
  get target() { return this._target; }
  set target(value) {
    this._target = String(value || '');
    this.attributes.set('target', this._target);
  }
  get rel() { return this._rel; }
  set rel(value) {
    this._rel = String(value || '');
    this.attributes.set('rel', this._rel);
  }
  closest(selector) {
    if (selector.includes('a[href]') && this.tagName === 'A' && this.href) return this;
    if (selector.includes('form[action]') && this.tagName === 'FORM') return this;
    if (selector.includes('form') && this.tagName === 'FORM') return this;
    if (selector.includes('button') && this.tagName === 'BUTTON') return this;
    if (selector.includes('video') && this.tagName === 'VIDEO') return this;
    if (selector.includes('audio') && this.tagName === 'AUDIO') return this;
    if (selector.includes('div') && this.tagName === 'DIV') return this;
    if (selector.includes('span') && this.tagName === 'SPAN') return this;
    if (selector.includes('a') && this.tagName === 'A') return this;
    if (selector.includes('[onclick]') && this.hasAttribute('onclick')) return this;
    if (selector.includes('[role="button"]') && this.getAttribute('role') === 'button') return this;
    if (selector.includes('[role="link"]') && this.getAttribute('role') === 'link') return this;
    return null;
  }
  matches(selector) {
    return Boolean(this.closest(selector));
  }
  querySelector() { return null; }
  getAttribute(name) { return this.attributes.get(name) ?? null; }
  setAttribute(name, value) {
    const normalized = String(name);
    const stringValue = String(value);
    this.attributes.set(normalized, stringValue);
    if (normalized === 'href') this._href = stringValue;
    if (normalized === 'target') this._target = stringValue;
    if (normalized === 'rel') this._rel = stringValue;
  }
  removeAttribute(name) {
    this.attributes.delete(name);
    if (name === 'href') this._href = '';
    if (name === 'target') this._target = '';
    if (name === 'rel') this._rel = '';
  }
  hasAttribute(name) { return this.attributes.has(name); }
  getBoundingClientRect() { return this._rect; }
}

class FakeHTMLElement extends FakeElement {}
installNativeEventHandlerDescriptors(FakeHTMLElement.prototype);
class FakeForm extends FakeHTMLElement {
  constructor(options = {}) {
    super({ tagName: 'FORM', ...options });
    this.nativeSubmitCount = 0;
    this.nativeRequestSubmitCount = 0;
    this.action = options.action || options.attrs?.action || '';
    this.target = options.target || options.attrs?.target || '';
  }
  submit() {
    this.nativeSubmitCount += 1;
    return true;
  }
  requestSubmit() {
    this.nativeRequestSubmitCount += 1;
    return true;
  }
}

class FakeAnchor extends FakeHTMLElement {
  constructor(options = {}) {
    super({ tagName: 'A', ...options });
    this.nativeClickCount = 0;
  }
  click() {
    this.nativeClickCount += 1;
    const event = new FakeEvent('click', {
      cancelable: true,
      target: this,
      path: [this]
    });
    return this.dispatchEvent(event);
  }
}

class FakeFrameWindow extends FakeEventTarget {
  constructor(origin, activation) {
    super();
    this.location = { href: `${origin}/about-blank-frame`, origin };
    this.navigator = { userActivation: activation };
    this.nativeOpenCount = 0;
    this.document = { defaultView: this };
  }
  open() {
    this.nativeOpenCount += 1;
    return { native: true, close() {}, focus() {} };
  }
}

class FakeIFrame extends FakeHTMLElement {
  constructor(frameWindow) {
    super({ tagName: 'IFRAME', connected: false });
    this._frameWindow = frameWindow;
  }
  get contentWindow() { return this._frameWindow; }
  get contentDocument() { return this._frameWindow.document; }
}

function createContext(host = 'filma24.stream') {
  const origin = `https://${host}`;
  const activation = { isActive: false };
  let nativeOpenCount = 0;

  class FakeDocument extends FakeEventTarget {
    constructor() {
      super();
      this.referrer = '';
      this.documentElement = new FakeHTMLElement({ tagName: 'HTML' });
      this.body = new FakeHTMLElement({ tagName: 'BODY' });
    }
    createElement(localName) {
      const name = String(localName || '').toLowerCase();
      if (name === 'iframe') return new FakeIFrame(new FakeFrameWindow(origin, activation));
      if (name === 'a') return new FakeAnchor();
      return new FakeHTMLElement({ tagName: name || 'div' });
    }
    createElementNS(_namespace, qualifiedName) {
      return this.createElement(String(qualifiedName || '').split(':').pop());
    }
  }

  installNativeEventHandlerDescriptors(FakeDocument.prototype);

  class FakeWindow extends FakeEventTarget {
    constructor() {
      super();
      this.location = { href: `${origin}/watch`, origin };
      this.navigator = { userActivation: activation };
    }
    open() {
      nativeOpenCount += 1;
      return { native: true, close() {}, focus() {} };
    }
  }

  installNativeEventHandlerDescriptors(FakeWindow.prototype);

  const document = new FakeDocument();
  const window = new FakeWindow();
  const context = {
    console,
    URL,
    Proxy,
    Reflect,
    Object,
    Function,
    Date,
    Set,
    WeakSet,
    WeakMap,
    Number,
    String,
    Boolean,
    Symbol,
    Event: FakeEvent,
    CustomEvent: FakeCustomEvent,
    EventTarget: FakeEventTarget,
    Document: FakeDocument,
    Window: FakeWindow,
    document,
    location: window.location,
    navigator: window.navigator,
    innerWidth: 1280,
    innerHeight: 720,
    Element: FakeElement,
    HTMLElement: FakeHTMLElement,
    HTMLAnchorElement: FakeAnchor,
    HTMLFormElement: FakeForm,
    HTMLIFrameElement: FakeIFrame,
    getComputedStyle(element) { return element._style; },
    window,
    self: window,
    top: window,
    parent: window
  };
  vm.createContext(context);
  vm.runInContext(source, context, { filename: 'page-guard.js' });
  return {
    context,
    document,
    window,
    activation,
    nativeOpenCount: () => nativeOpenCount
  };
}

function trustedEvent(type, document, target) {
  return new FakeEvent(type, {
    cancelable: true,
    isTrusted: true,
    target,
    path: [target, document]
  });
}

function trustedClick(document, target) {
  const event = trustedEvent('click', document, target);
  document.dispatchEvent(event);
  return event;
}

{
  const { window, nativeOpenCount } = createContext();
  const result = window.open('https://popads.net/zone?zoneid=9', '_blank');
  assert.equal(nativeOpenCount(), 0, 'known pop-under destination must not open');
  assert.equal(result.location.href, 'about:blank');
  assert.doesNotThrow(() => { result.location.href = 'https://popcash.net/'; });
  assert.doesNotThrow(() => { result.location.replace('https://popcash.net/'); });
  assert.equal(result.location.href, 'about:blank', 'dummy Window location must remain inert');
  assert.equal(result.opener, null, 'dummy Window must not expose the real opener');
}

{
  const { window, activation, nativeOpenCount } = createContext();
  activation.isActive = true;
  const result = window.open('https://checkout.stripe.com/pay', '_blank');
  assert.equal(nativeOpenCount(), 1, 'protected checkout must be allowed');
  assert.equal(result.native, true);
}

{
  const { window, document, nativeOpenCount } = createContext();
  const anchor = new FakeAnchor({ href: 'https://example.org/article' });
  trustedClick(document, anchor);
  const result = window.open('https://example.org/article', '_blank');
  assert.equal(nativeOpenCount(), 0, 'programmatic external window.open must not inherit trust from an anchor gesture');
  assert.equal(result.location.href, 'about:blank');
}

{
  const { window, nativeOpenCount } = createContext('example.com');
  const result = window.open('https://unrelated.example.net/', '_blank');
  assert.equal(nativeOpenCount(), 0, 'unrequested cross-origin window must be blocked');
  assert.equal(result.location.href, 'about:blank');
}

{
  const { document } = createContext();
  let unloadRan = 0;
  assert.doesNotThrow(() => {
    document.addEventListener('unload', () => { unloadRan += 1; });
  }, 'restricted unload listener registration must never throw');
  document.dispatchEvent(new FakeEvent('unload'));
  assert.equal(unloadRan, 0, 'unload listeners must be ignored by the guard');

  let suspiciousRan = 0;
  document.addEventListener('mouseup', function obfuscatedGlobalPopunder(event) {
    const payload = 'popunder';
    window.open('https://popads.net/zone?zoneid=88', '_blank');
    event.preventDefault();
    suspiciousRan += payload.length;
  });
  document.dispatchEvent(new FakeEvent('mouseup'));
  assert.equal(suspiciousRan, 0, 'obfuscated global pop-under listener must be defused');
}

{
  const { document } = createContext();
  const iframe = document.createElement('iframe');
  assert.equal(Object.hasOwn(iframe, 'contentWindow'), true, 'dynamic iframe must be armed at creation time');
  const frameWindow = iframe.contentWindow;
  const blocked = frameWindow.open('https://popcash.net/click?campaignid=7', '_blank');
  assert.equal(frameWindow.nativeOpenCount, 0, 'dynamic iframe contentWindow.open must be guarded before use');
  assert.equal(blocked.location.href, 'about:blank');

  const namespacedIframe = document.createElementNS('http://www.w3.org/1999/xhtml', 'iframe');
  const namespacedFrameWindow = namespacedIframe.contentWindow;
  namespacedFrameWindow.open('https://adsterra.com/popunder?clickid=1', '_blank');
  assert.equal(namespacedFrameWindow.nativeOpenCount, 0, 'createElementNS iframe must also be guarded');
}

{
  const { context, activation } = createContext('example.com');
  activation.isActive = true;
  const visibleExternalAnchor = new context.HTMLAnchorElement({
    href: 'https://developer.mozilla.org/en-US/docs/Web/API/Window/open',
    target: '_blank',
    text: 'Open documentation',
    connected: true
  });
  const result = visibleExternalAnchor.click();
  assert.equal(result, false, 'programmatic external _blank navigation must be destination-locked');
  assert.equal(visibleExternalAnchor.nativeClickCount, 0, 'scripted anchor.click must not initialize an external tab');

  const nativeEvent = trustedEvent('click', context.document, visibleExternalAnchor);
  context.document.dispatchEvent(nativeEvent);
  assert.equal(nativeEvent.defaultPrevented, false, 'ordinary user-driven visible anchor navigation must remain functional');
}

{
  const { context, activation } = createContext();
  activation.isActive = true;
  const anchor = new context.HTMLAnchorElement({
    href: 'https://popads.net/zone?zoneid=90',
    target: '_blank',
    connected: false
  });
  const blockedClickResult = anchor.click();
  assert.equal(blockedClickResult, false, 'blocked anchor.click must return false');
  assert.equal(anchor.nativeClickCount, 0, 'programmatic hostile anchor.click must be neutralized');

  const rotatingAd = new context.HTMLAnchorElement({
    href: 'https://rotating-ad-domain.example/landing',
    target: '_blank',
    connected: false
  });
  rotatingAd.click();
  assert.equal(rotatingAd.nativeClickCount, 0, 'detached external _blank click must be blocked on aggressive hosts');

  const protectedAnchor = new context.HTMLAnchorElement({
    href: 'https://checkout.stripe.com/pay',
    target: '_blank',
    connected: false
  });
  protectedAnchor.click();
  assert.equal(protectedAnchor.nativeClickCount, 1, 'protected programmatic navigation must remain functional');
}

{
  const { context, activation } = createContext();
  activation.isActive = true;
  const anchor = new context.HTMLAnchorElement({
    href: 'https://onclicka.com/campaign?clickid=77',
    target: '_blank',
    connected: false
  });
  let listenerRan = 0;
  anchor.addEventListener('click', () => { listenerRan += 1; });
  const event = new FakeEvent('click', {
    cancelable: true,
    target: anchor,
    path: [anchor]
  });
  const dispatched = anchor.dispatchEvent(event);
  assert.equal(dispatched, false, 'hostile programmatic dispatchEvent must report cancellation');
  assert.equal(event.defaultPrevented, true, 'hostile programmatic click must be prevented');
  assert.equal(listenerRan, 0, 'hostile programmatic click listeners must not execute');
}

{
  const { context, activation } = createContext('example.com');
  activation.isActive = true;
  const externalForm = new context.HTMLFormElement({
    action: 'https://untrusted-popup.example/landing',
    target: '_blank',
    attrs: { action: 'https://untrusted-popup.example/landing', target: '_blank' }
  });
  assert.equal(externalForm.submit(), false, 'external programmatic _blank form submission must be destination-locked');
  assert.equal(externalForm.nativeSubmitCount, 0, 'blocked form.submit must not reach the native backend');
  assert.equal(externalForm.requestSubmit(), false, 'external programmatic requestSubmit must be destination-locked');
  assert.equal(externalForm.nativeRequestSubmitCount, 0, 'blocked requestSubmit must not reach the native backend');

  const protectedForm = new context.HTMLFormElement({
    action: 'https://checkout.stripe.com/pay',
    target: '_blank',
    attrs: { action: 'https://checkout.stripe.com/pay', target: '_blank' }
  });
  protectedForm.submit();
  assert.equal(protectedForm.nativeSubmitCount, 1, 'protected checkout form must remain functional');
}

{
  const { context, document, window, nativeOpenCount } = createContext();
  const video = new context.HTMLElement({ tagName: 'VIDEO' });
  let playbackBranchRuns = 0;
  document.addEventListener('click', function combinedPlayerAndPopupHandler() {
    playbackBranchRuns += 1;
    window.open('https://rotating-ad-domain.example/landing', '_blank');
  });
  const event = trustedEvent('click', document, video);
  document.dispatchEvent(event);
  assert.equal(playbackBranchRuns, 1, 'media playback branch inside a suspicious handler must still execute');
  assert.equal(nativeOpenCount(), 0, 'media-origin external popup must be destination-locked');
  assert.equal(event.defaultPrevented, true, 'blocked popup branch must cancel the external navigation gesture');
}

{
  const { context, document, window, activation, nativeOpenCount } = createContext();
  activation.isActive = true;
  const video = new context.HTMLElement({ tagName: 'VIDEO' });
  let checkoutBranchRuns = 0;
  document.addEventListener('click', function protectedMediaCheckoutHandler() {
    checkoutBranchRuns += 1;
    window.open('https://checkout.stripe.com/pay', '_blank');
  });
  const event = trustedEvent('click', document, video);
  document.dispatchEvent(event);
  assert.equal(checkoutBranchRuns, 1, 'protected media-origin flow must execute');
  assert.equal(nativeOpenCount(), 1, 'protected checkout destination must remain authorized');
}

{
  const { context, document, window, nativeOpenCount } = createContext();
  let directHandlerRuns = 0;
  window.onclick = function popunderWindowProperty(event) {
    directHandlerRuns += 1;
    window.open('https://popads.net/zone?zoneid=143', '_blank');
    event.preventDefault();
  };

  const target = new context.HTMLElement({ tagName: 'DIV', text: 'Player surface' });
  const event = new FakeEvent('click', {
    cancelable: true,
    isTrusted: true,
    target,
    path: [target, document, window]
  });
  window.dispatchEvent(event);
  assert.equal(event.defaultPrevented, true, 'dangerous window.onclick gesture must be swallowed');
  assert.equal(event._immediateStopped, true, 'dangerous window.onclick gesture must stop immediately');
  assert.equal(directHandlerRuns, 0, 'dangerous window.onclick handler must not execute');
  assert.equal(nativeOpenCount(), 0, 'dangerous direct handler must not initialize a popup target');
}

{
  const { context, nativeOpenCount } = createContext();
  const element = new context.HTMLElement({ tagName: 'DIV', text: 'Watch' });
  let runs = 0;
  element.onpointerdown = function directPointerPopunder(event) {
    runs += 1;
    window.open('https://onclicka.com/campaign?clickid=143', '_blank');
    event.preventDefault();
  };
  const event = new FakeEvent('pointerdown', {
    cancelable: true,
    isTrusted: true,
    target: element,
    path: [element]
  });
  const dispatched = element.dispatchEvent(event);
  assert.equal(dispatched, false, 'dangerous HTMLElement.onpointerdown must cancel dispatch');
  assert.equal(event.defaultPrevented, true, 'direct property wrapper must prevent default');
  assert.equal(runs, 0, 'dangerous element property handler must be defused');
  assert.equal(nativeOpenCount(), 0, 'element property handler must not open a native tab');
}

{
  const { context, document, window } = createContext();
  const element = new context.HTMLElement({ tagName: 'DIV', text: 'Player' });
  element.onpointerdown = function pointerdownPopunder(event) {
    window.open('https://popads.net/zone?zoneid=144', '_blank');
    event.preventDefault();
  };
  let trailingClickRuns = 0;
  window.addEventListener('click', () => { trailingClickRuns += 1; }, true);

  const pointerdown = new FakeEvent('pointerdown', {
    cancelable: true,
    isTrusted: true,
    target: element,
    path: [element, document, window]
  });
  window.dispatchEvent(pointerdown);
  assert.equal(pointerdown.defaultPrevented, true, 'hostile pointerdown must be canceled');

  const click = new FakeEvent('click', {
    cancelable: true,
    isTrusted: true,
    target: element,
    path: [element, document, window]
  });
  window.dispatchEvent(click);
  assert.equal(click.defaultPrevented, true, 'trailing click from a blocked pointer sequence must be canceled');
  assert.equal(trailingClickRuns, 0, 'gesture quarantine must suppress the trailing click before page capture listeners');
}

{
  const { context } = createContext('example.com');
  const button = new context.HTMLElement({ tagName: 'BUTTON', text: 'Save' });
  let legitimateRuns = 0;
  button.onclick = function legitimateClick() {
    legitimateRuns += 1;
  };
  const event = new FakeEvent('click', {
    cancelable: true,
    isTrusted: true,
    target: button,
    path: [button]
  });
  button.dispatchEvent(event);
  assert.equal(legitimateRuns, 1, 'ordinary direct click handlers must remain functional');
  assert.equal(event.defaultPrevented, false, 'ordinary direct click handlers must not be canceled');
}

{
  const { document } = createContext();
  const overlay = new FakeHTMLElement({
    tagName: 'DIV',
    attrs: { class: 'ad-overlay clickunder-layer' },
    rect: { width: 1280, height: 720 },
    style: {
      position: 'fixed',
      opacity: '0.01',
      backgroundColor: 'rgba(0, 0, 0, 0)',
      zIndex: '2147483647'
    },
    connected: true
  });
  let hostileListenerRan = 0;
  document.addEventListener('click', () => { hostileListenerRan += 1; }, true);
  const event = trustedEvent('click', document, overlay);
  document.dispatchEvent(event);
  assert.equal(event.defaultPrevented, true, 'trusted click on invisible overlay must be prevented in capture phase');
  assert.equal(event._immediateStopped, true, 'trusted overlay click must stop immediate propagation');
  assert.equal(hostileListenerRan, 0, 'overlay listener must not receive the user gesture token');
}

{
  const { context, document } = createContext();
  const video = new context.HTMLElement({ tagName: 'VIDEO', text: '' });
  let mediaClickRuns = 0;
  document.addEventListener('click', () => { mediaClickRuns += 1; }, true);
  const event = trustedEvent('click', document, video);
  document.dispatchEvent(event);
  assert.equal(event.defaultPrevented, false, 'trusted HTML5 media interaction must retain its user gesture');
  assert.equal(mediaClickRuns, 1, 'media player click handlers must remain functional on aggressive hosts');
}


{
  const { window, document, context, nativeOpenCount } = createContext('www.youtube.com');
  const originalOpen = window.open;
  const result = window.open('https://rcdn-web.com/ad', '_blank');
  assert.equal(nativeOpenCount(), 1, 'trusted first-party application origins must keep their native window runtime');
  assert.equal(result.native, true, 'YouTube application context must remain untouched by MAIN-world popup hooks');
  assert.equal(window.open, originalOpen, 'YouTube window.open must not be replaced');

  let frameworkSignalRuns = 0;
  document.addEventListener('click', () => { frameworkSignalRuns += 1; });
  const playerSurface = new context.HTMLElement({ tagName: 'DIV', attrs: { id: 'movie_player', class: 'html5-video-player' } });
  document.dispatchEvent(trustedEvent('click', document, playerSurface));
  assert.equal(frameworkSignalRuns, 1, 'trusted platform framework events must pass natively');
}

{
  const { context, window, activation, nativeOpenCount } = createContext();
  activation.isActive = true;
  const trustedDestinations = [
    'https://www.youtube.com/watch?v=M7lc1UVf-VE',
    'https://redirector.googlevideo.com/videoplayback?id=1',
    'https://i.ytimg.com/vi/M7lc1UVf-VE/hqdefault.jpg',
    'https://yt3.ggpht.com/avatar',
    'https://player.twitch.tv/?channel=example',
    'https://www.netflix.com/watch/1'
  ];
  for (const destination of trustedDestinations) {
    const result = window.open(destination, '_blank');
    assert.equal(result.native, true, `trusted platform destination must pass: ${destination}`);
  }
  assert.equal(nativeOpenCount(), trustedDestinations.length, 'only explicitly trusted platform destinations must reach native window.open');

  const youtubeAnchor = new context.HTMLAnchorElement({
    href: 'https://www.youtube.com/watch?v=M7lc1UVf-VE',
    target: '_blank',
    connected: false
  });
  youtubeAnchor.click();
  assert.equal(youtubeAnchor.nativeClickCount, 1, 'programmatic YouTube destination must remain compatible');

  const hostileAnchor = new context.HTMLAnchorElement({
    href: 'https://rcdn-web.com/landing?clickid=147',
    target: '_blank',
    connected: false
  });
  assert.equal(hostileAnchor.click(), false, 'trusted-platform calibration must not loosen ad-matrix anchor blocking');
  assert.equal(hostileAnchor.nativeClickCount, 0);
}


assert.match(source, /externalDestinationLocked/, 'target-based destination lock must be bundled');
assert.match(source, /starveActivePopupGesture/, 'popup gesture starvation must be bundled');
assert.match(source, /MEDIA_FRAMEWORK_SOURCE/, 'media framework detection must be bundled');
assert.match(source, /inspectBinaryMediaPart/, 'binary media segment detection must be bundled');
assert.match(source, /mediaSafe/, 'worker and Blob analysis must expose a media-safe path');
assert.match(source, /TRUSTED_APPLICATION_ORIGINS/, 'trusted first-party application bypass must be bundled');
assert.match(source, /TRUSTED_PLATFORM_DESTINATIONS/, 'trusted platform destination families must be bundled');
assert.match(source, /googlevideo\.com|googlevideo.com/, 'YouTube media delivery safelist must be bundled');

console.log('PASS · page guard smoke tests');
