Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

2.6 KB
Raw Blame
import { coerceToString } from "metabase/utils/scripts-sandbox/coerce";
import {
  CREATE_ELEMENT,
  CREATE_ELEMENT_NS,
  getXmlElementLocalName,
} from "metabase/utils/scripts-sandbox/distortions-dom-mutate";

const isStyleTag = (tag: string) => tag.toLowerCase() === "style";

function isStyleQualifiedName(qualifiedName: string) {
  return isStyleTag(getXmlElementLocalName(qualifiedName));
}

/** The shared sandbox distortion callback, as the membrane types it. */
type SharedDistortion = (value: object) => object;

export function makeCreateElementDistortion(
  value: typeof CREATE_ELEMENT,
  shared: SharedDistortion,
): typeof CREATE_ELEMENT;
export function makeCreateElementDistortion(
  value: typeof CREATE_ELEMENT_NS,
  shared: SharedDistortion,
): typeof CREATE_ELEMENT_NS;
export function makeCreateElementDistortion(
  value: object,
  shared: SharedDistortion,
): object | null;
export function makeCreateElementDistortion(
  value: object,
  shared: SharedDistortion,
): object | null {
  if (value === CREATE_ELEMENT) {
    // A distortion callback is typed `object -> object` (the membrane erases the
    // call signature), so restore the signature of the ref it stands in for.
    const sharedCreateElement = shared(value) as typeof CREATE_ELEMENT;

    return function createElement(
      this: Document,
      tag: string,
      options?: ElementCreationOptions,
    ) {
      const tagName = coerceToString(tag);
      // Data-app bundles inline imported CSS with
      // `vite-plugin-css-injected-by-js`, which creates a `<style>` tag at
      // runtime. Allow only that tag while keeping the shared dangerous-tag
      // blocklist for `script` and other DOM creation.
      if (isStyleTag(tagName)) {
        return CREATE_ELEMENT.call(this, tagName, options);
      }

      return sharedCreateElement.call(this, tagName, options);
    };
  }

  if (value === CREATE_ELEMENT_NS) {
    // Same signature restoration as above: `shared` hands back a drop-in
    // replacement for `createElementNS`, typed only as `object`.
    const sharedCreateElementNS = shared(value) as typeof CREATE_ELEMENT_NS;

    return function createElementNS(
      this: Document,
      namespaceURI: string | null,
      qualifiedName: string,
      options?: ElementCreationOptions,
    ) {
      const name = coerceToString(qualifiedName);
      if (isStyleQualifiedName(name)) {
        // Same exception as `createElement("style")`, but for namespaced
        // creation paths.
        return CREATE_ELEMENT_NS.call(this, namespaceURI, name, options);
      }

      return sharedCreateElementNS.call(this, namespaceURI, name, options);
    };
  }

  return null;
}