// The two ways the loader's guards put their own function in front of a browser
// built-in (a method like fetch or setAttribute, or the setter of a property like
// document.cookie or img.src), and take it out again. Each returns the undo
// function, which puts the original back only if the replacement is still the
// current one: another copy of the loader may have wrapped it since, and
// restoring over that would undo its guard.

/** Sets `target[key]` to `value` without throwing. A writable property a page
 * locked (`configurable: false`) is assigned to; anything else is defined, which
 * also works on a property a page made read-only but left configurable and keeps
 * the other flags (such as `enumerable`) of one that exists. False when the
 * property cannot be changed at all. */
function put(target: object, key: PropertyKey, value: unknown): boolean {
  try {
    if (Object.getOwnPropertyDescriptor(target, key)?.configurable === false) {
      Reflect.set(target, key, value);
      return Reflect.get(target, key) === value;
    }
    Object.defineProperty(target, key, {
      configurable: true,
      writable: true,
      value,
    });
    return true;
  } catch {
    return false;
  }
}

/** Replaces `target[key]` with `make(original)`. A property that cannot be
 * changed is left alone (the undo then does nothing), so one locked-down member
 * never stops the other guards from starting. */
export function wrapMember<T extends object, K extends keyof T>(
  target: T,
  key: K,
  make: (original: T[K]) => T[K],
): () => boolean {
  const original = target[key];
  const wrapped = make(original);
  if (!put(target, key, wrapped)) return () => true;
  // True when the original is back (or there was nothing to put back); false when
  // another wrapper sits on top, so ours is still in the chain.
  return () => {
    if (target[key] !== wrapped) return false;
    put(target, key, original);
    return true;
  };
}

type Setter = (this: unknown, value: unknown) => void;

/** Replaces the setter of the accessor property `key` on `target` with
 * `make(original)`. Does nothing (and the undo does nothing) when there is no
 * setter to wrap, or when the property is locked. */
export function wrapSetter(
  target: object,
  key: string,
  make: (original: Setter) => Setter,
): () => void {
  const descriptor = Object.getOwnPropertyDescriptor(target, key);
  const original = descriptor?.set;
  if (!descriptor || !original) return () => undefined;
  const wrapped = make(original);
  try {
    Object.defineProperty(target, key, { ...descriptor, set: wrapped });
  } catch {
    // A locked accessor cannot be wrapped; the other guards still start.
    return () => undefined;
  }
  return () => {
    if (Object.getOwnPropertyDescriptor(target, key)?.set === wrapped) {
      Object.defineProperty(target, key, descriptor);
    }
  };
}
