'use strict';

const featureFlagController = require('./feature-flag-controller-09933b7a.js');
const log = require('./global-slimmer-registry-7bbdb1f2.js');
const typography = require('./typography-4560e7f1.js');
const staticSubjectTitle = require('./static-subject-title-5829a298.js');
const changeManager = require('./change-manager-72f643de.js');
const observer = require('./observer-f49483e8.js');
const index = require('./index-58ea899e.js');
const en = require('./internal-translation-controller-38f68a4c.js');
const vegaEnvManager = require('./vega-env-manager-23b8b23c.js');
const vegaNonceManager = require('./vega-nonce-manager-55854929.js');
const themeManager = require('./theme-manager-991ba9c1.js');

var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * The `VegaWatchMethodCancelSlimmer` class is a TypeScript class that removes
 * the body of watch methods when a component is not fully instantiated and
 * applies the original method body when the component is fully instantiated.
 */
class VegaWatchMethodCancelSlimmer extends log.VegaSlimmer {
  /**
   * The constructor function takes a component object as a parameter and assigns it to the "component"
   * property of the class.
   *
   * @param {GlobalSlimmerConfig} option - The `option` parameter is of type `GlobalSlimmerConfig`.
   * It is an object that represents a component in a software system.
   */
  constructor(option) {
    super();
    this.originalWatchers = new Map();
    /**
     * while component reattached, the component will call `connectedCallback` but not call `componentDidLoad`,
     * so we add this flag to skip empty the watch function in this case.
     */
    this.hasDisconnected = false;
    this.isEnabled = featureFlagController.FeatureFlag.isEnabled('VEGA_REACT.PREVENT_CALL_WATCH_METHOD_BEFORE_COMPONENT_LOAD') &&
      featureFlagController.FeatureFlag.isEnabled('VEGA_FRAMEWORK.PREVENT_CALL_WATCH_METHOD_BEFORE_COMPONENT_LOAD');
    this.component = option.component;
  }
  /**
   * The connectedCallback function removes the body of watch methods when the component is not fully
   * instantiated.
   */
  connectedCallback() {
    if (!this.isEnabled)
      return;
    if (this.hasDisconnected)
      return;
    const watchers = this.component.constructor['watchers'];
    for (const propName in watchers) {
      const watchMethodNames = watchers[propName];
      watchMethodNames.forEach((methodName) => {
        // while watch method listen by multiple property, we should skip make originalMethod as empty.
        if (!this.originalWatchers.has(methodName)) {
          const originalMethod = this.component[methodName];
          this.originalWatchers.set(methodName, originalMethod);
          /**
           * Remove the watch method body when the component not fully instantiated.
           */
          // eslint-disable-next-line @typescript-eslint/no-empty-function
          this.component[methodName] = function () { };
        }
      });
    }
  }
  /**
   * The `@MapToComponentMethod('disconnectedCallback')` decorator is used to map the `disconnectedCallback` method
   * to the corresponding method in the Stencil component.
   */
  disconnectedCallback() {
    if (!this.isEnabled)
      return;
    this.hasDisconnected = true;
  }
  /**
   * The `componentDidLoad` function applies the original method body to the component's watchers when
   * the component is fully instantiated.
   */
  componentDidLoad() {
    if (!this.isEnabled)
      return;
    this.originalWatchers.forEach((method, methodName) => {
      const originalMethodBody = method;
      /**
       * Apply the watch original method body when the component fully instantiated.
       *
       * @param {...any} args - watch method args
       * @returns {unknown} method results
       */
      this.component[methodName] = function (...args) {
        return originalMethodBody.apply(this, args);
      };
    });
  }
}
__decorate$2([
  log.MapToComponentMethod('connectedCallback')
], VegaWatchMethodCancelSlimmer.prototype, "connectedCallback", null);
__decorate$2([
  log.MapToComponentMethod('disconnectedCallback')
], VegaWatchMethodCancelSlimmer.prototype, "disconnectedCallback", null);
__decorate$2([
  log.MapToComponentMethod('componentDidLoad')
], VegaWatchMethodCancelSlimmer.prototype, "componentDidLoad", null);

var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * Class responsible for observing translation updates and triggering re-renders.
 */
class VegaTranslateObserverSlimmer extends log.VegaSlimmer {
  constructor(option) {
    super();
    this.component = option.component;
  }
  /**
   * Component lifecycle - [connectedCallback]
   * Registers an observer to watch for translation updates, which triggers a forced update on the component.
   */
  connectedCallback() {
    this.observer = new observer.Observer(this.isAcceptable.bind(this), () => {
      index.forceUpdate(this.component);
    });
    changeManager.ChangeManager.register(staticSubjectTitle.UPDATE_TRANSLATION, this.observer);
  }
  /**
   * Component lifecycle - [disconnectedCallback]
   * Unregister the observer when the component is disconnected from the DOM.
   */
  disconnectedCallback() {
    if (this.observer) {
      changeManager.ChangeManager.unregister(staticSubjectTitle.UPDATE_TRANSLATION, this.observer);
      this.observer = null;
    }
  }
  /**
   * Determines whether the observer should accept changes.
   *
   * @returns {boolean} Always returns true in the current implementation.
   */
  isAcceptable() {
    var _a, _b;
    const host = this.component['host'];
    return (_b = (_a = en.VegaInternalTranslation.getConnectedComponents().get(host.tagName)) === null || _a === void 0 ? void 0 : _a.has(host)) !== null && _b !== void 0 ? _b : false;
  }
}
__decorate$1([
  log.MapToComponentMethod('connectedCallback')
], VegaTranslateObserverSlimmer.prototype, "connectedCallback", null);
__decorate$1([
  log.MapToComponentMethod('disconnectedCallback')
], VegaTranslateObserverSlimmer.prototype, "disconnectedCallback", null);

var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * Class responsible for injecting nonce into inline style attributes for vega components.
 */
class VegaNonceInjectorSlimmer extends log.VegaSlimmer {
  constructor(option) {
    super();
    this.component = option.component;
  }
  /**
   * Component lifecycle - [connectedCallback]
   * Registers an observer to watch for translation updates, which triggers a forced update on the component.
   */
  /**
   * Lifecycle callback that is invoked when the custom element is added to the DOM.
   *
   * This implementation overrides the `insertBefore` method of the element's shadow root
   * to automatically set the `nonce` attribute on any inline `<style>` elements that are inserted.
   * This is typically used to support Content Security Policy (CSP) by ensuring that dynamically
   * injected styles have the correct nonce value.
   */
  connectedCallback() {
    const shadowRoot = this.component['host'].shadowRoot;
    // override element#insertBefore to set nonce attribute for inline style element
    const originalInsertBefore = shadowRoot.insertBefore;
    /**
     * Overrides the shadowRoot's insertBefore method to inject a CSP nonce into any STYLE element being inserted.
     *
     * @template T - The type of Node being inserted.
     * @param {T} newElement - The new node to insert.
     * @param {Node | null} referenceElement - The node before which newElement is inserted, or null to insert at the end.
     * @returns {T} The inserted node.
     */
    shadowRoot.insertBefore = function (newElement, referenceElement) {
      if (newElement.nodeName === 'STYLE') {
        const nonce = vegaNonceManager.vegaNonceManager.nonce;
        if (nonce !== undefined) {
          newElement.setAttribute('nonce', nonce);
        }
      }
      return originalInsertBefore.call(this, newElement, referenceElement);
    };
  }
}
__decorate([
  log.MapToComponentMethod('connectedCallback')
], VegaNonceInjectorSlimmer.prototype, "connectedCallback", null);

/* eslint-disable @typescript-eslint/naming-convention, @typescript-eslint/typedef, jsdoc/require-jsdoc, jsdoc/require-param-type, jsdoc/require-returns-type, jsdoc/require-returns, jsdoc/tag-lines, spellcheck/spell-checker */
/**
 * VegaModuleLoader provides a lazy loading mechanism for Vega's public API modules.
 *
 * Instead of eagerly injecting all modules into `globalThis` at startup (as `vega.esm.js`
 * does for backward compatibility), consumers can use the lean entry (`vega-lean.esm.js`)
 * which registers only `VegaModuleLoader` on `globalThis`, then load modules on demand:
 *
 * ```js
 * const VegaThemeManager = await VegaModuleLoader.load('VegaThemeManager');
 * ```
 *
 * This results in significantly smaller initial bundle sizes for vanilla JS consumers
 * who only need a subset of Vega's public API modules.
 *
 * VegaModuleLoader is available in ALL entry points (full browser, lean browser,
 * and framework loaders), so it can be used alongside eager injection too.
 *
 * ⚠ AUTO-GENERATED — do not edit manually.
 *   Source of truth: src/global/scripts/vanilla-js-global-setup.ts
 *   Generator:       scripts/generate-vega-module-loader.js
 *   Re-generate:     yarn generate:module-loader
 */
/**
 * Registry mapping module names to their dynamic import factories.
 * Each factory returns a Promise that resolves to the module's exported value.
 * The dynamic `import()` calls enable Rollup code-splitting — modules are
 * only loaded when `VegaModuleLoader.load()` is called.
 */
const MODULE_REGISTRY = {
  VegaLoader: () => Promise.resolve().then(function () { return require('./vega-loader-controller-9c15d69f.js'); }).then(m => m.VegaLoader),
  VegaNotify: () => Promise.resolve().then(function () { return require('./vega-notify-controller-7d60f1c9.js'); }).then(m => m.VegaNotify),
  VegaThemeManager: () => Promise.resolve().then(function () { return require('./theme-manager-991ba9c1.js'); }).then(m => m.VegaThemeManager),
  setVegaLogLevel: () => Promise.resolve().then(function () { return require('./global-slimmer-registry-7bbdb1f2.js'); }).then(function (n) { return n.log; }).then(m => m.setVegaLogLevel),
  VegaDialog: () => Promise.resolve().then(function () { return require('./vega-dialog-controller-3c2248da.js'); }).then(m => m.VegaDialog),
  VegaEventManager: () => Promise.resolve().then(function () { return require('./vega-event-manager-fb12c460.js'); }).then(m => m.default),
  VegaIconManager: () => Promise.resolve().then(function () { return require('./icon-manager-d14c9a96.js'); }).then(m => m.VegaIconManager),
  VegaZIndexManager: () => Promise.resolve().then(function () { return require('./vega-z-index-manager-78137014.js'); }).then(m => m.default),
  ValidCreditCardNumberRule: () => Promise.resolve().then(function () { return require('./valid-credit-card-number-rule-86ebac2b.js'); }).then(m => m.ValidCreditCardNumberRule),
  waitForVega: () => Promise.resolve().then(function () { return require('./wait-for-vega-handler-e138576f.js'); }).then(m => m.waitForVega),
  VegaSkeletonLoader: () => Promise.resolve().then(function () { return require('./vega-skeleton-loader-controller-fd470958.js'); }).then(m => m.VegaSkeletonLoader),
  VegaTranslation: () => Promise.resolve().then(function () { return require('./translation-bce24a14.js'); }).then(m => m.VegaTranslation),
  VegaTranslationResourceEN: () => Promise.resolve().then(function () { return require('./internal-translation-controller-38f68a4c.js'); }).then(function (n) { return n.en; }).then(m => m.default),
  VegaRTEContent: () => Promise.resolve().then(function () { return require('./content-state-09ffae92.js'); }).then(function (n) { return n.contentState; }).then(m => m.VegaRTEContent),
  VegaRTETokenExtension: () => Promise.resolve().then(function () { return require('./token-extension-85b62a11.js'); }).then(function (n) { return n.tokenExtension; }).then(m => m.VegaRTETokenExtension),
  VegaRTELanguageExtension: () => Promise.resolve().then(function () { return require('./language-extension-5a44c74c.js'); }).then(function (n) { return n.languageExtension; }).then(m => m.VegaRTELanguageExtension),
  VegaRTEPresetToolbarItems: () => Promise.resolve().then(function () { return require('./constant-57b1ce36.js'); }).then(m => m.VegaRTEPresetToolbarItems),
  VegaRTEFunctionExtension: () => Promise.resolve().then(function () { return require('./function-extension-75c3611d.js'); }).then(m => m.VegaRTEFunctionExtension),
  VegaRTETableExtension: () => Promise.resolve().then(function () { return require('./table-extension-76fe6a50.js'); }).then(m => m.VegaRTETableExtension),
  setVegaNonce: () => Promise.resolve().then(function () { return require('./vega-nonce-manager-55854929.js'); }).then(m => m.setVegaNonce),
  VegaValidationRules: () => Promise.resolve().then(function () { return require('./public-rules-73dcc51d.js'); }),
  FeatureFlag: () => Promise.resolve().then(function () { return require('./feature-flag-controller-09933b7a.js'); }).then(m => m.FeatureFlag),
};
const moduleCache = new Map();
const VegaModuleLoader = {
  /**
   * Lazily load a Vega module by name.
   *
   * @param moduleName - The name of the module to load (e.g. 'VegaThemeManager')
   * @returns A Promise that resolves to the module's value
   *
   * @example
   * ```js
   * const VegaThemeManager = await VegaModuleLoader.load('VegaThemeManager');
   * VegaThemeManager.applyBranding('gp');
   * ```
   */
  async load(moduleName) {
    var _a;
    // Check cache first
    if (moduleCache.has(moduleName)) {
      return moduleCache.get(moduleName);
    }
    // Check if already available on globalThis (backward compat with full entry).
    // Guard against the browser's "named access on the Window object" feature,
    // which auto-exposes DOM elements with an `id` as `window[id]` properties.
    // E.g. `<vega-button id="VegaThemeManager">` would make
    // `window.VegaThemeManager` return the DOM element instead of the module.
    // Uses nodeType === 1 instead of instanceof Element for cross-environment
    // compatibility (Stencil mock-doc, jsdom, browser).
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    if (globalThis[moduleName] !== undefined && ((_a = globalThis[moduleName]) === null || _a === void 0 ? void 0 : _a.nodeType) !== 1) {
      moduleCache.set(moduleName, globalThis[moduleName]);
      return globalThis[moduleName];
    }
    const factory = MODULE_REGISTRY[moduleName];
    if (!factory) {
      throw new Error(`VegaModuleLoader: Unknown module "${moduleName}". ` +
        `Available modules: ${Object.keys(MODULE_REGISTRY).join(', ')}`);
    }
    const module = await factory();
    moduleCache.set(moduleName, module);
    return module;
  },
  /**
   * Returns the list of all available module names that can be loaded.
   */
  getAvailableModules() {
    return Object.keys(MODULE_REGISTRY);
  },
};

// eslint-disable-next-line spellcheck/spell-checker
/**
 * Default export function that will be used by stencil global script,
 * which will be invoked before library loaded.
 *
 * This lean version only contains essential setup that ALL consumers need:
 * - Feature flag configuration from client globals
 * - Global slimmers (component lifecycle hooks)
 * - Typography injection
 * - Telemetry initialization (VegaEnvInfo + runtime metrics)
 * - CSP nonce head patch
 * - VegaModuleLoader on globalThis (for on-demand lazy loading of public API modules)
 * - Apply branding from client global (via VegaModuleLoader, zero static-import cost)
 *
 * The heavier vanilla-JS-only globalThis injections are handled separately
 * by vanillaJsGlobalSetup (only in `vega.esm.js`, the full browser entry).
 * Consumers who want a leaner bundle can use `vega-lean.esm.js` instead.
 */
function appGlobalScript () {
  disableFeatureFlagFromClientGlobal();
  enableFeatureFlagFromClientGlobal();
  registerGlobalVegaSlimmers();
  injectVegaTypography();
  initRuntimeMetricsTelemetryCollection();
  patchHeadInsertBeforeWithNonce();
  exposeVegaModuleLoader();
  applyBrandingFromClientGlobal();
}
/**
 * Disable feature flags from the client global defined lists.
 */
function disableFeatureFlagFromClientGlobal() {
  if (globalThis['VegaDisabledFeatureKeys']) {
    featureFlagController.FeatureFlag.disable(...globalThis['VegaDisabledFeatureKeys']);
  }
}
/**
 * This function enables feature flags based on a global variable in TypeScript.
 */
function enableFeatureFlagFromClientGlobal() {
  if (globalThis['VegaEnabledFeatureKeys']) {
    featureFlagController.FeatureFlag.enable(...globalThis['VegaEnabledFeatureKeys']);
  }
}
/**
 * register global vega slimmers
 */
function registerGlobalVegaSlimmers() {
  log.GlobalSlimmersRegistry.register([
    VegaWatchMethodCancelSlimmer,
    VegaTranslateObserverSlimmer,
    VegaNonceInjectorSlimmer,
  ]);
}
/**
 * Inject Vega typography stylesheet
 */
function injectVegaTypography() {
  Object.keys(typography.TypographyUrls).forEach((key) => {
    const { url } = typography.TypographyUrls[key];
    const typographyLinkId = `vega-typography-${key}`;
    // eslint-disable-next-line no-restricted-globals
    if (!document.querySelector(`#${typographyLinkId}`)) {
      // eslint-disable-next-line no-restricted-globals
      const typographyLink = document.createElement('link');
      typographyLink.id = typographyLinkId;
      typographyLink.href = url;
      typographyLink.rel = 'stylesheet';
      // eslint-disable-next-line no-restricted-globals
      document.head.append(typographyLink);
    }
  });
}
/**
 * init telemetry runtime metrics.
 * 1. Inject VegaEnvInfo to global (used by vega-telemetry-runtime-metrics for environment tracking)
 * 2. Register runtime metrics add page hide listener method
 */
function initRuntimeMetricsTelemetryCollection() {
  globalThis.VegaEnvInfo = vegaEnvManager.vegaEnvManager.getVegaEnv();
  // eslint-disable-next-line spellcheck/spell-checker
  void Promise.resolve().then(function () { return require('./index-f054eb5d.js'); }).then((
  // eslint-disable-next-line spellcheck/spell-checker
  module) => {
    module['default']['init'](featureFlagController.FeatureFlag);
  });
}
/**
 * Patch document.head.insertBefore to ensure nonce is set on injected elements.
 */
function patchHeadInsertBeforeWithNonce() {
  vegaNonceManager.vegaNonceManager.patchHeadInsertBeforeWithNonceToStencil();
}
/**
 * Expose VegaModuleLoader on globalThis so vanilla JS consumers using the lean entry
 * can load public API modules on demand:
 *
 * ```js
 * const VegaThemeManager = await VegaModuleLoader.load('VegaThemeManager');
 * ```
 *
 * VegaModuleLoader has no static imports — all module references use dynamic import(),
 * so adding it here does not increase the lean bundle's initial load size.
 */
function exposeVegaModuleLoader() {
  globalThis['VegaModuleLoader'] = VegaModuleLoader;
}
/**
 * Switch the Vega theme to a new brand theme from the client global defined options.
 *
 * This runs synchronously so that branding is guaranteed to be applied before
 * any component renders, in both the lean and full entries.
 */
function applyBrandingFromClientGlobal() {
  if (globalThis['VegaThemeManagerApplyBranding']) {
    themeManager.VegaThemeManager.applyBranding(globalThis['VegaThemeManagerApplyBranding']);
  }
}

const globalScripts = appGlobalScript;

exports.globalScripts = globalScripts;
